Quantcast
Channel: Scott Hanselman's Blog
Viewing all articles
Browse latest Browse all 1148

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

$
0
0

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!



© 2016 Scott Hanselman. All rights reserved.
     

Viewing all articles
Browse latest Browse all 1148

Trending Articles