Scott Hanselman

Exploring ServiceStack's simple and fast web services on .NET Core

October 23, '16 Comments [22] Posted in Open Source | Web Services
Sponsored By

Northwind - ServiceStack styleI'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.

ServiceStack Logo

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:

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.

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.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb
Sunday, 23 October 2016 09:35:13 UTC
ServiceStack is indeed a wonderful framework! We have been using it for years. Almost never a glitch, and if there is, it's easy to get fixed, especially since the source is available.

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.
David A. Sjøen
Sunday, 23 October 2016 10:18:44 UTC
No, I didn't use ServiceStack until now, but will definitely give it a shot when I find the time. A leaner way of approaching services is always welcome :-)
Thanks Scott!
Kristof Berger
Sunday, 23 October 2016 11:06:40 UTC
Thanks for the great write-up 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.
Demis Bellot
Sunday, 23 October 2016 11:20:03 UTC
@Demis, I saw that after commenting. However, it could probably be clearer, like for instance putting a reference to the *.Core packages in the description of the 4.5.2 packages.

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!
David A. Sjøen
Sunday, 23 October 2016 17:41:05 UTC
We've been using ServiceStack for 5 years now, can't say enough good things about it!
Sunday, 23 October 2016 19:16:27 UTC
I love your technical articles but you are missing the executive summary on the last few. You assume we all know [Insert Random Tech] in this case ServiceStack. Even their website is not easy to understand. Times have changed, we need understandable messages / sales pitches. You can not assume we have all been playing in the same playground for the past 10 years. From what I have gathered this is a WebAPI replacement, why would this benefit me?
Chris Go
Sunday, 23 October 2016 19:49:26 UTC
@Chris It's impossible to distill ServiceStack down into a single summary, it's an entire Software ecosystem that's designed to be simple, code-first and integrated. If you're looking for a quick overview checkout the opening paragraphs on ServiceStack's project page: https://github.com/ServiceStack/ServiceStack

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.
Demis Bellot
Sunday, 23 October 2016 19:55:40 UTC
Interesting. The ServiceStack Todo example reminds me of Finagle/Finch in the JVM/Scala world. The todo example in Finch.

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.
Yawar
Monday, 24 October 2016 09:29:26 UTC
*Huge* ServiceStack fan and have been a user/customer for years and years and it's been great watching it grow and move from open source (still available I think) to a paid product.

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.
Monday, 24 October 2016 10:36:16 UTC
It's great that your doing a demo on servicestack Scott.

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!
Joel harkes
Monday, 24 October 2016 11:19:07 UTC
We've used ServiceStack at quite big microservice project and it was a real bliss to work with. I think, if I ever be back to .net developement, that would me my go-to framework. BTW, my first OSS pull-request was into ServiceStack.Text. )))
Victor Suzdalev
Monday, 24 October 2016 13:02:45 UTC
Link to ServiceStack.OrmLite is wrong, it should be: https://github.com/ServiceStack/ServiceStack.OrmLite
Vitor Barbosa
Monday, 24 October 2016 14:10:51 UTC
Is there a Pluralsight class on this ServiceStack within VisualStudio. Maybe a simple walk-through and setup?
Chris Go
Monday, 24 October 2016 15:11:06 UTC
@Chris There are links to PluralSight courses published on the home page servicestack.net/#pluralsight but ServiceStack is actively developed with frequent releases where many of these courses contains dated functionality but the core concepts remain the same.

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.
Demis Bellot
Monday, 24 October 2016 17:49:25 UTC
@Demis Bellot Thanks, when I have a few days free I will dig in, haha.
Chris Go
Monday, 24 October 2016 21:35:47 UTC
I do not think I would ever use ServiceStack. There's no value proposition that I can see. Not sure why it is being called out here, when there are heaps of awesome OSS projects in the .NET space which are much easier to get internal approval for. Disappointed to see this sales pitch on this blog.
Dave
Monday, 24 October 2016 23:20:11 UTC
Dave - Sorry you felt this was a sales pitch. I disagree. I have no sales relationship with them and I gain nothing from sharing ServiceStack with you. If you don't like it, don't use it.

That said, I'll be showcasing a number of OSS Projects (larger frameworks, in fact) in the coming weeks. Maybe you'll dig those.
Scott Hanselman
Tuesday, 25 October 2016 00:41:19 UTC
@Dave If you don't see value in something, please don't use it. We never want anyone to adopt ServiceStack who don't feel like they're getting value from it. But we strongly believe ServiceStack does deliver a tonne of value to the thousands of developers using ServiceStack, even with a cursory glance it's not hard to find value proposition in a simple, stable, integrated Software platform that's been in active development for over 8 years with a unique feature-set not found elsewhere - most of which is effortless to enable as a consequence of ServiceStack's design.

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.
Demis Bellot
Tuesday, 25 October 2016 02:11:07 UTC
Scott - I'm looking forward to the future showcases. I will also step back from my comment that this post was a Sales pitch.
Dave
Tuesday, 25 October 2016 14:59:41 UTC
Wondering if Microsoft should maybe acquire ServiceStack and make their templates available for free within Visual Studio? Remember saying this about Xamarin 5 years ago and it took Microsoft ages to actually get around to it. Similar to Xamarin prior to acquisition, ServiceStack have a pricing model that is probably prohibitive to most Enterprise developers (a lot of whom are working on Shoestring budgets). Would be great if Microsoft moved on this quickly as a way of bringing and promoting more standardised, best practices into Enterprise development with Visual Studio?
Andy Poots
Wednesday, 26 October 2016 14:35:04 UTC
I've been using ServiceStack for years now and I love it, awesome to see it on .net core!
John
Monday, 07 November 2016 17:55:21 UTC
A magnificent post, my congratulations. I think I will be very useful this information.

Thanks!
Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.