Exploring ServiceStack's simple and fast web services on .NET Core
I've been doing .NET Open Source since the beginning. Trying to get patches into log4net was hard without things like GitHub and Twitter. We emailed .patch files around and hoped for the best. It was a good time.
There's been a lot of feelings around .NET Open Source over the last decade or so - some positive, some negative. There's been some shining lights though and I'm going to do a few blog posts to call them out. I think having .NET Core be cross platform and open source will be a boon for the .NET Community. However, the community needs to also help out by using non-Microsoft OSS, supporting it, doing PRs, helping with docs, giving talks on new tech and spreading the word.
While some OSS projects are purely volunteer projects, ServiceStack has found some balance with a per-developer pricing model. They also support free usage for small projects. They've got deep integration with all major IDEs and support everything from VS, Xcode, IntelliJ IDEA, and the commandline.
One major announcement in the least few days as been ServiceStack 4.5.2 on .NET Core! Effectively one year to the day from the feature request and they did it! Their announcement paragraph says it best, emphasis mine.
Whilst the development and tooling experience is still in a transitionary period we believe .NET Core puts .NET Web and Server App development on the cusp of an exciting future - the kind .NET hasn’t seen before. The existing Windows hosting and VS.NET restraints have been freed, now anyone can develop using .NET’s productive expertly-designed and statically-typed mainstream C#/F# languages in their preferred editor and host it on the most popular server Operating Systems, in either an all-Linux, all-Windows or mixed ecosystem. Not only does this flexibility increase the value of existing .NET investments but it also makes .NET appeal to the wider and highly productive developer ecosystem who’ve previously disregarded .NET as an option.
Many folks ran (and run) ServiceStack on Mono, but it's time to move forward. While Mono is still a fantastic stack on many platforms that .NET Core doesn't support, for mainstream Linux, .NET Core is likely the better choice.
If you’re currently running ServiceStack on Mono, we strongly recommend upgrading to .NET Core to take advantage of its superior performance, stability and its top-to-bottom supported Technology Stack.
I also want to call out ServiceStack's amazing Release Notes. Frankly, we could all learn from Release Note this good - Microsoft absolutely included. These release notes are the now Gold Standard as far as I'm concerned. Additionally, ServiceStack's Live Demos are unmatched.
Enough gushing. What IS ServiceStack? It's a different .NET way for creating web services. I say you should give it a hard look if you're making Web Services today. They say this:
Service Stack provides an alternate, cleaner POCO-driven way of creating web services.
- Simplicity
- Speed
- Best Practices
- Model-driven, code-first, friction-free development
- No XML config, no code-gen, conventional defaults
- Smart - Infers intelligence from strongly typed DTOs
- .NET and Mono
- Highly testable - services are completely decoupled from HTTP
- Mature - over 5+ years of development
- Commercially supported and Continually Improved
- and most importantly - with AutoQuery you get instant queryable APIs. Take a look at what AutoQuery does for a basic Northwind sample.
They've plugged into .NET Core and ASP.NET Core exactly as it was design. They've got sophisticated middleware and fits in cleanly and feels natural. Even more, if you have existing ServiceStack code running on .NET 4.x, they've designed their "AppHost" such that moving over the .NET Core is extremely simple.
ServiceStack has the standard "Todo" application running in both .NET Full Framework and .NET Core. Here's two sites, both .NET and both ServiceStack, but look what's underneath them:
- http://todos.netcore.io - Linux / Docker / nginx / .NET Core
- http://todos.servicestack.net - Windows / IIS / .NET 4.5 / ASP.NET
Getting Started with Service Stack
There's a million great demos as I mentioned above with source at https://github.com/NetCoreApps, but I love that ServiceStack has a Northwind Database demo here https://github.com/NetCoreApps/Northwind. It even includes a Dockerfile. Let's check it out. I was able to get it running in Docker in seconds.
>git clone https://github.com/NetCoreApps/Northwind
>cd Northwind
>docker build -t "northwindss/latest" .
>docker run northwindss/latest
Project Northwind.ServiceModel (.NETStandard,Version=v1.6) was previously compiled. Skipping compilation.
Project Northwind.ServiceInterface (.NETStandard,Version=v1.6) was previously compiled. Skipping compilation.
Project Northwind (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Hosting environment: Production
Content root path: /app/Northwind
Now listening on: https://*:5000
Application started. Press Ctrl+C to shut down.
Let's briefly look at the code, though. It is a great sample and showcases a couple cool features and also is nicely RESTful.
- OrmLite Sqlite
- Multiple automatic built-in Content-Types
- Custom Media Types - Adding vcard format
- CachedService
There's some cool techniques in here. It uses SqLITE for the database and the database itself is created with this Unit Test. Here's the ServiceStack AppHost (AppHost is their concept)
public class AppHost : AppHostBase
{
public AppHost() : base("Northwind Web Services", typeof(CustomersService).GetAssembly()) { }
public override void Configure(Container container)
{
container.Register<IDbConnectionFactory>(
new OrmLiteConnectionFactory(MapProjectPath("~/App_Data/Northwind.sqlite"), SqliteDialect.Provider));
//Use Redis Cache
//container.Register<ICacheClient>(new PooledRedisClientManager());
VCardFormat.Register(this);
Plugins.Add(new AutoQueryFeature { MaxLimit = 100 });
Plugins.Add(new AdminFeature());
Plugins.Add(new CorsFeature());
}
}
Note host the AppHost base references the Assembly that contains the CustomersService type. That's the assembly that is the ServiceInterface. There's a number of Services in there - CustomersService just happens to be a simple one:
public class CustomersService : Service
{
public object Get(Customers request) =>
new CustomersResponse { Customers = Db.Select<Customer>() };
}
The response for /customers is just the response and a list of Customers:
[DataContract]
[Route("/customers")]
public class Customers : IReturn<CustomersResponse> {}
[DataContract]
public class CustomersResponse : IHasResponseStatus
{
public CustomersResponse()
{
this.ResponseStatus = new ResponseStatus();
this.Customers = new List<Customer>();
}
[DataMember]
public List<Customer> Customers { get; set; }
[DataMember]
public ResponseStatus ResponseStatus { get; set; }
}
Customers has a lovely clean GET that you can see live here: http://northwind.netcore.io/customers. Compare its timestamp to the cached one at http://northwind.netcore.io/cached/customers.
[CacheResponse(Duration = 60 * 60, MaxAge = 30 * 60)]
public class CachedServices : Service
{
public object Get(CachedCustomers request) =>
Gateway.Send(new Customers());
public object Get(CachedCustomerDetails request) =>
Gateway.Send(new CustomerDetails { Id = request.Id });
public object Get(CachedOrders request) =>
Gateway.Send(new Orders { CustomerId = request.CustomerId, Page = request.Page });
}
You may find yourself looking at the source for the Northwind sample and wondering "where's the rest?" (no pun intended!) Turns out ServiceStack will do a LOT for you if you just let it!
The Northwind project is also an example of how much can be achieved with a minimal amount of effort and code. This entire website literally just consists of these three classes . Everything else seen here is automatically provided by ServiceStack using a code-first, convention-based approach. ServiceStack can infer a richer intelligence about your services to better able to provide more generic and re-usable functionality for free!
ServiceStack is an alternative to ASP.NET's Web API. It's a different perspective and a different architecture than what Microsoft provides out of the box. It's important and useful to explore other points of view when designing your systems. It's especially nice when the systems are so thoughtfully factored, well-documented and designed as ServiceStack. In fact, years ago I wrote their tagline: "Thoughtfully architected, obscenely fast, thoroughly enjoyable web services for all."
Have you used ServiceStack? Have you used other open source .NET Web Service/API frameworks? Share your experience in the comments!
Sponsor: Big thanks to Telerik! 60+ ASP.NET Core controls for every need. The most complete UI toolset for x-platform responsive web and cloud development. Try now 30 days for free!
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
Thanks Scott!
@David This is covered in the release notes, all packages available in .NET Core are listed at: http://docs.servicestack.net/releases/v4.5.2.html#net-core-servicestack-packages
They're maintained in separate `*.Core` packages for now until they've been battle-tested in the wild in order for them to be on a separate release cadence without disrupting existing .NET 4.5 Customers. It's also recommended to reference all ServiceStack's .NET Core packages using the "1.0.*" wildcard version string so `dotnet restore` automatically pulls down the latest version.
I made a .NET Core test project a couple of days ago, and thought I could use ServiceStack 4.5.2, based on a commit message I saw in the ServiceStack.OrmLite repo. As that failed, I incorrectly concluded that it wasn't available yet.
Anyway, looking forward to try it out!
It can be used to build ASP.NET Web App, Self-Hosted Console Apps, Windows Services, Windows and Mac Desktop Apps, Single Page Apps or the back-end to Xamarin and Native iOS/Android Apps where it integrates with each major IDE used for native Mobile App development to enable a simple, clean end-to-end API in C#, Swift, Java and Kotlin out-of-the-box. But it does a whole lot more as best captured by the top comment on the DotNetRocks show on ServiceStack http://www.dotnetrocks.com/?show=1204.
If you want to explore ServiceStack's major features checkout the Highlights Section servicestack.net/#spotlights which lists a number of major features made possible because of it's message-based design.
They seem to share a similar philosophy: have a domain model class (Todo) with a backing data store; have a service which declares and implements the API endpoints; and finally have a server which knows what to serve based on the service definitions.
If you take this idea to its extreme of simplicity, you get something like this, where the domain model is a simple record type, the API endpoint service is literally a single function that handles the different cases of the record type, and the server is another function that automatically handles encoding and decoding for the JSON-to-data roundtrip.
Actually now that I think about it, there's a really fun native F# HTTP server stack: Suave.
Submitted a pull request once when I needed something and it was accepted straight away.
Demis always seems active and helps people on twitter and other forums.
So impressed with the CoreClr port as am I with CoreClr itself. Visual Studio Code on a Mac with C# is a nice place to be.
Good work all.
I've recently been using servicestack to its full potential. Although I'm enthusiastic about the framework I think some parts can be thoughtfully refactored to be les static and more atomic (mostly around the apphost and routing). Never the less it is a great framework with many great features out of the box.
The best part about ServiceStack is the message based architecture. It really helps you think of you program as an api first. then later adding an ui to this api is very easy.
I've been contributing (small parts) recently and I'd like to thank Demis (mythz) personally for being very open to pull requests and ideas.
Its definitely a framework you could consider.
Great post Scott!
The docs contains the easiest way to Get Started which is to install ServiceStackVS VS.NET extension and select one of the many ServiceStack VS.NET Templates which gets you up and running with a pre-configured ServiceStack solution out of the gate.
That said, I'll be showcasing a number of OSS Projects (larger frameworks, in fact) in the coming weeks. Maybe you'll dig those.
We very much appreciate the surprise exposure here from Scott (awareness is something that has historically plagued adoption of many quality libraries in .NET) - but since your comment suggests otherwise, I want to make it very clear this isn't a sales pitch and ServiceStack has never paid for a sponsored post/comment/quote/endorsement/etc ever, nor have we ever paid for any marketing/advertising/evangelists to-date. All our efforts and resources have been solely focused on product development which is what's resulted in ServiceStack's vast number of features (but still have lot more to cover). You can rest assured that any endorsements you've seen on ServiceStack are going to be real experiences from users deriving real value from ServiceStack. Not something I want to have to point out, but feel it's necessary here to address the misinformation.
Thanks!
Comments are closed.
However, v4.5.2 isn't on .NET Core, is it? Seems like there is a separate .NET Core version, ServiceStack.Core, which is at version 1.0.23 right now.