⬆️ ⬇️

How ServiceStack helps put the development of web services on stream

On Habré undeservedly overlooked the remarkable .Net-framework ServiceStack. He will be mentioned very briefly, in only one article , and then indirectly, briefly, and at the very end, and only a tiny part of it is mentioned there. Obviously, this is due to the fact that the majority of .Net developers use standard Microsoft solutions to solve problems in developing web services and web applications, namely ASP.Net MVC / WebAPI or WCF and do not bother. As we will try to show in this article, modern .Net is good not only for its standard technologies.







If interested, please under the cat.

')

So, we will fill this gap with this review article, and in the end we will try to make something with our own hands using this tool, which we successfully use in our practice , and I must say, are very satisfied.



ServiceStack? No, have not heard...





First, let's answer the question what the ServiceStack itself is. This is a full-fledged framework for creating web services and web applications, which incorporates the best from the world of C # and ASP.Net, and - yes, you guessed it! - get rid of all the worst, superfluous and unnecessary. However, dear habrazhitel, let us warn right away that there will be no holivar, not this Thursday and not with us! Looking ahead, we note that there are architectural variations that combine components into a single system, written both on ServiceStack (as a server) and, for example, on ASP.Net MVC (as a client).



The framework originated in the bowels of the BBC company, at the time Demis Bellot worked there. The beginning of the development of the framework can be considered the year 2007, when the BBC, which uses standard Enterprise solutions from Microsoft, coupled with a waterfall approach to development in the context of rapidly changing requirements, got straight into the problem, and “prosak” is closer to the definition given by Nikita Migalkov’s movie “ Dead Man's Silence ”, rather than to the definition from the Explanatory Dictionary *







This prosak was that in order to make every small change, it was necessary to go through a cycle from UML to a code that took them up to several days, every crutch for compatibility of formats between old records and new ones, and weekly idle times between major releases.



The team has set itself a simple question: what is the service after all? The question is not complicated in principle, and many of us will give the same answers to it, namely:







This is what a service is by definition. In addition to this, good service should be conducive to upcoming changes, should be designed so that making changes is not a problem.



Reflections on this issue led to the birth of ServiceStack, which allowed only half of the team to achieve greater results than the entire team before.



And yet, why is he better?









Regarding the last point, one should, of course, make a reservation that with the presence of direct hands, a high level of code reuse can also be achieved using standard Microsoft solutions. However, this requires, again, straight arms, and the right approach, and experience. Thanks to the simplicity and comparative genius of the ServiceStack architecture, less qualified developers can achieve better results and also cultivate a commitment to more efficient approaches to code structuring.



And, probably, for some the next moment will be completely decisive:







ServiceStack projects can be deployed to Linux right out of the box!



Thus, you do not even have to pay for expensive Windows Azure or, even more expensive, to have your own Windows Server. For a medium-sized project, a regular server can be useful, for example, with Debian or Ubuntu Server, or even a Hetzner VPS for $ 30 per month . For smaller projects, the cheapest $ 10 VPS will go to Hetzner or even $ 5 to Digital Ocean .



Our partners have experience in deploying and hosting ServiceStack projects on Linux using nginx + FastCGI Mono, and if we are all interested in, if we ask them together, I think they will not refuse us to tell us about This is done in detail.



Can I have more technical details?



It is impossible. The developers of ServiceStack did not begin to tear down the entire ASP.Net in the bud, in order to build something new. The root - namely IHttpHandler - they left. However, all that goes further and destroyed and used more lightweight alternatives, which in some places themselves have been slightly adapted specifically for solving the problems of developing a web service. The framework provides its cash manager, its authentication and session providers, and even offers its own MQ-broker working on the basis of Redis. By the way, within the framework of the framework, we also created our own Redis client , which, in my personal opinion, is simply gorgeous, and it can be used separately from the framework in different contexts. As a regular IOC container, a slightly modified version of Func’s sufficiently popular lightweight container is used . True, instead of it, you can use any other IOC-container from the set available.



The corestones of the ServiceStack are the DTO (Data Transfer Objects), which are based on flat POCO objects. Authentication and session providers, as well as user services, are based on POCO, which allows using different backends for different implementations. Out of the box, for example, typed sessions are available for storage directly in memory and in Redis. An untyped session is also available for lovers of dynamism, but unfortunately it works somewhat slower.



Unfortunately, it is impossible to consider the framework architecture in a single article in detail, but if there is interest from inquisitive habrovchan, we could write a series of articles about this in the future. In the meantime, let's write a small HelloWorld to tease the reader's appetite.



Good to pour water, let's code!



So, in order to create a web service in a ServiceStack project, you need to do four simple things, namely:





Let's write a simple service.



Create a new project in Visual Studio or Xamarin Studio. In the absence of the first one at hand, I will use the second one, good, under Mono everything works great (and initially this factor was decisive for us). And as compensation for not using the best IDE, we will show you how to use this service from the mobile application for the best mobile OS.



So, create an empty ASP.Net project (Empty Web Application). We call the solution SSHelloWorld, and the project - SSHelloAPI.



For the project in the Solution Explorer (Solution Explorer), right-click, and select “Manage Nuget Packages”.







After you click on the “Add” button, you will be asked if you agree with the license agreement? Well, because Russian-speaking users read license agreements faster than anyone else, we agree, and ServiceStack downloaded dlls are connected to our project.



If there is no Global.asax in your project (and in theory it should be absent), add it and copy the following code into Global.asax.cs instead:



using System; using System.Collections; using System.ComponentModel; using System.Web; using System.Web.SessionState; using ServiceStack; namespace SSHelloAPI { public class Global : System.Web.HttpApplication { public class AppHost : AppHostBase { public AppHost() : base("Hello API", typeof(HelloService).Assembly) {} public override void Configure (Funq.Container container) { } } protected void Application_Start (Object sender, EventArgs e) { new AppHost ().Init (); } } } 




Do not pay attention to highlighting errors in the code now. We need to create a class in which our service will be located.



You will also likely have to manually create the web.config file . And all its code should be replaced by the following:



 <?xml version="1.0"?> <configuration> <system.web> <httpHandlers> <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*"/> </httpHandlers> </system.web> <!-- Required for IIS 7.0 (and above?) --> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" /> </handlers> </system.webServer> </configuration> 




And finally, we will create a new HelloService.cs file, in which we will have three classes:



 using System; using ServiceStack; namespace SSHelloAPI { [Route("/hello")] [Route("/hello/{Name}")] public class HelloRequest { public string Name { get; set; } } public class HelloResponse { public string Result { get; set; } } public class HelloService : Service { public object Any(HelloRequest request) { return new HelloResponse { Result = "Hello, " + request.Name }; } } } 




Everything is simple and clear, I am even ashamed to comment on such code. We compile and run our project, and in the address bar of the browser we enter after the host name and port “/ hello / Habrauser”. ServiceStack on the request header itself determines the type of client, and in this case will show us the response of the service in the html wrapper. And in the Result field we will see how the service greets us.



The name of the method Any says that we have defined the same logic for all HTTP methods.



Pay attention to the metadata page, which opens first of all when the project is launched. It contains automatically generated service documentation. As you can see, ServiceStack creates various endpoints on the go, and we can work with our service with both the RESTful service and the SOAP service (yes, I mean SOAP, dear reader).







The service, of course, is boring, but in order not to overload the article, we did not immediately include more complex examples. However, it makes you feel the taste of SericeStack and if you were interested, now you can try more with or without us.



How ServiceStack makes life easier for a mobile developer





What ServiceStack is good about is that it is very convenient to use the created service on Windows Phone, Xamarin.iOS or Xamarin.Android-application (though, the last two require a business license for Xamarin). There are various ways, but the simplest (but not the most beautiful) is to separate the classes of Requests and Responses into separate files, and connect them via linking to a mobile application project. Also from Nuget install the assembly ServiceStack.Client.



Next, let's say on the button press event we hang such a handler:



  button.TouchUpInside += (object sender, EventArgs e) => { try { var client = new JsonServiceClient("http://127.0.0.1:8080"); HelloResponse response = client.Get<HelloResponse>(new HelloRequest() { Name = "iPhone" }); resultLabel.Text = response.Result; } catch (Exception ex) { resultLabel.Text = ex.Message; } }; 




This issue can also be considered in more detail in the future.



And what about the license?





Starting from version 4.0, the project has acquired a commercial color. Well, why not, if it makes it better? The source code of the framework remains open, however, the license allows the framework to be used free of charge only for small projects with the following restrictions:







Well, okay, not a single Redis, except for OrmLite there are other ORMs, but 10 operations is already a significant, of course, limiting.



More information on licensing and pricing is available on this page .



At the moment we are using the 3rd version in our projects, which is available under the BSD license, and we are only considering the transition to 4th. If you do not want to be tied to the “commercial side”, you can safely take the 3rd branch and use it in your project, it is quite mature and stable.



References and footnotes



PROSAK (Dahl Dictionary) m. Nov. hard spinning mill; twisted, rope, rope mill, on which they twist, lower the ropes. || * The predicament, poor thing, where you do not know how to be. He got into a mess, he got into a mess. Prosak (from a bitch?), The space from the spinning wheel to the sleigh, where the whipwind twirls and twirls, a line descends; if you get there with the end of your clothes, your hair, you will twist it and you will not run out; from this saying.



But seriously, here they are:



Official site

servicestack.net



Wiki

github.com/ServiceStack/ServiceStack/wiki



Slideshow with Demis Belloth's presentation on ServiceStack

www.slideshare.net/newmovie



Some examples of working projects (the code is open and available on github)

Analogue imgur

imgur.servicestack.net



RestMovies

mono.servicestack.net/ServiceStack.MovieRest



Analog StackOverflow

mono.servicestack.net/RedisStackOverflow



And many other examples are available on this page , and their sources on github .



And if it has become interesting for you, dear reader, and you are eager to learn more, you just say it, and we - with joint efforts - will continue to develop and open the topic with pleasure.

Source: https://habr.com/ru/post/213389/



All Articles