CTS – Your Technology Partner

Getting Started with ServiceStack: Part 1

Written by Lydon Bergin on April 23, 2014

ServiceStack Introduction:

ServiceStack is a config-free, code-first web and services framework embraced around Martin Fowler’s remote-service best-practices in idiomatic C#. Its message-based design provides the most advantages for remote services encapsulating them in their most re-usable form allowing the same service to be called in REST, SOAP, MQ services enabling .NET’s most succinct, end-to-end typed API.

ServiceStack’s Web Services Framework is an alternative to WCF, WCF/REST, .asmx, Web-API, MVC, WebForms, WebPages, CSF, WSE, WCF DataServices, RIA Services, and System.Messaging.

ServiceStack’s OrmLite is a set of light-weight C# extension methods around System.Data.* interfaces which is designed to persist POCO (Plain Old CLR Object) classes with a minimal amount of intrusion and configuration.

ServiceStack is designed to be “obscenely fast” – According to 3rd Party Benchmarks, OrmLite is 12 times faster than Entity Framework, and the ServiceStack.Text JSON Serializer is 6 times faster than the .NET DataContractJsonSerializer.

Part 1: Installation & Configuration

Create Empty Project

In order to get started with the ServiceStack Web Services Framework, we should start with an Empty ASP.NET Web Application. Open Visual Studio (I’m using 2013) and create a new project using the “ASP.NET Empty Web Application Template” as shown in the figure below.

clip_image002

Install ServiceStack Libraries Using NuGet

Now that we have an empty project, we need to add references to the ServiceStack libraries that we will be using. The easiest way to do this is by using the NuGet Package Manager to install the libraries and their dependencies. Right-Click on your project in the Solution Explorer and select Manage NuGet Packages.

clip_image004

Once the NuGet Package Manager opens, search for “ServiceStack” – the package that we want to install is “ServiceStack webservice framework”, click the Install button to install the ServiceStack package and its dependencies.

clip_image006

You must accept the license for ServiceStack and its dependencies, ServiceStack.Text, and ServiceStack.Client.

While we have NuGet open, we will also install ServiceStack’s ORM, OrmLite. In this project, we will use Microsoft SQL Server as our data source, so install the OrmLite.SqlServer package.

clip_image008

Again, you must accept the license.

As an alternative to SQL Server, which we will be using, OrmLite also supports the following databases:

  • –  SQL Server
  • –  MySQL
  • –  PostgreSQL
  • –  SqlLite (Windows and Mono)
  • –  Oracle
  • –  Firebird

Configuring ServiceStack Web Services Framework

Create a ServiceStack Application Host

Now that we have installed ServiceStack, the first step is to create a class that will act as our Application Host. Create a new class in your project named ApplicationHost.cs. This simple class allows ServiceStack to handle incoming requests for us.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using ServiceStack; // Note: This isn’t necessary since my project is in the ServiceStack namespace

 

namespace ServiceStack.QuickStart

{

    publicclassApplicationHost : AppHostHttpListenerBase

    {

        /// <summary>

        /// This default constructor passes the name of our service “PersonService” as

        /// well as all assemblies that need to be loaded – in this case we only need to

        /// use the current assembly so I have passed that using typeof()

        /// </summary>

        public ApplicationHost() : base(“PersonService”,typeof(ApplicationHost).Assembly)

        {

                       

        }

 

        /// <summary>

        /// This method is used to configure things like Inversion-of-Control Containers

        /// </summary>

        /// <param name=“container”></param>

        publicoverridevoid Configure(Funq.Container container)

        {

            // Not changing any defaults (for now), so we don’t need to implement this

        }

    }

}

The comments in the code above explain what each method does, but we will be coming back to this class soon for further explanation.

Create a Global Application Class

Next, create a Global Application Class (Global.asax) that will initialize the ApplicationHost class when the application starts. Right-click on your project and select Add > New Item, and choose the Global Application Class Template.

using System;

 

namespace ServiceStack.QuickStart

{

    publicclassGlobal : System.Web.HttpApplication

    {

        protectedvoid Application_Start(object sender, EventArgs e)

        {

            // Initialize the ApplicationHost class when the Application Starts

            newApplicationHost().Init();

        }

    }

}

The code above initializes the ApplicationHost class that we created before.

Update the Web.config File

Finally, update the Web.config file to enable ServiceStack’s httpHandlers:

<configuration>

  <system.web>

    <compilationdebug=”truetargetFramework=”4.5.1” />

    <httpRuntimetargetFramework=”4.5.1” />

    <!– httpHandlers added for ServiceStack, this will work for IIS6 and Below –>

    <httpHandlers>

      <addpath=”*type=”ServiceStack.HttpHandlerFactory, ServiceStackverb=”*“/>

    </httpHandlers>

  </system.web>

  <!– system.WebServer tag added for ServiceStack, this will work for IIS7 and Above –>

  <system.webServer>

    <modulesrunAllManagedModulesForAllRequests=”true“/>

    <validationvalidateIntegratedModeConfiguration=”false“/>

    <handlers>

      <addpath=”*name=”ServiceStack.Factory

           type=”ServiceStack.HttpHandlerFactory, ServiceStack

           verb=”*preCondition=”integratedMode

           resourceType=”UnspecifiedallowPathInfo=”true“/>

    </handlers>

  </system.webServer>

</configuration>

Notice that we have updated two separate sections of the Web.config file for use in both IIS 6 and below as well as IIS 7 and above.

Test ServiceStack

At this point, we have completed the initial configuration for the ServiceStack Web Services Framework. You can now run the application, and you should see the ServiceStack metadata information screen.

clip_image010

Congratulations! You have now completely configured the ServiceStack Web Services Framework!

Configuring ServiceStack OrmLite for SQL Server

Create a New SQL Server Database

We will now create a new SQL Server database, which OrmLite will use to store data. Right-click on your solution in the Solution Explorer and select Add > Add ASP.NET Folder > App_Data. This will create a new folder called App_Data under your solution. Right-Click on the new App_Data folder and select Add > New Item, and choose the SQL Server Database template from the Add New Item dialog box.

clip_image012

I named my database “PersonDB” since we will be persisting a Person class to the database.

Add Database Connection String to the Application

In order for our application to our new database, we must add a connection string to our application settings. Right-click on your solution and select Properties, which will open the properties window. Now click on the Settings tab and add a setting of type “ConnectionString”, and set the value to point to the PersonDB.mdf file we created, for example:

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PersonDB.mdf;Initial Catalog=PersonDB;Integrated Security=True

We will use this connection string later, so make a note of the Name (I used “LocalSQLConnectionString”).

Wire Up Data Access in the ApplicationHost.cs Class

Now that we have created our database and added the connection string to our web.config file, we need to wire up a database connection to our ServiceStack Application Host so that each of our services can use our database connection. The developers of ServiceStack recommend that this is done in the AppHostHttpListenerBase.Configure method (which is in our ApplicationHost.cs file), so navigate to the Configure method in your ApplicationHost.cs file.

Previously we created an empty configure method:

        /// <summary>

        /// This method is used to configure things like Inversion-of-Control Containers

        /// </summary>

        /// <param name=“container”></param>

        publicoverridevoid Configure(Funq.Container container)

        {

            // Not changing any defaults (for now), so we don’t need to implement this

        }

Now we need to use the “container” parameter to register our database connection. Funq.Container is a dependency injection container that we will use to pass our OrmLite Database Connection Factory into our Service classes. We do this using the container.Register method:

        /// <summary>

        /// This method is used to configure things like Inversion-of-Control Containers

        /// </summary>

        /// <param name=“container”>Inversion of control container</param>

        publicoverridevoid Configure(Funq.Container container)

        {

            // Add our IDbConnectionFactory to the container, this will

            // allow all of our services to share a single connection factory

            container.Register<IDbConnectionFactory>

                (newOrmLiteConnectionFactory

                    (Properties.Settings.Default.LocalSQLConnectionString,

                    SqlServerOrmLiteDialectProvider.Instance));

        }

Conclusion

In Part 1, we installed and configured the ServiceStack Web Services Framework and ServiceStack OrmLite. In Part 2 we will create a simple data access layer using ServiceStack’s OrmLite ORM.

Comments

comments