Sponsored by Gluten Free Waffles and Sliced Bananas

Tuesday, April 2, 2013

ASP.NET Web API, Autofac & Self-Hosting

8:40 PM Posted by Tyson Nero , , , , 23 comments

Well Structured Projects

Separation of concerns comes into play even when laying out the projects in your code solution. For instance, you may have separate projects for your contract classes (DTOs), data layer, service layer, and sometimes even finer granularity among those.

When building such projects using ASP.NET's Web API for example, you may be tempted to lump everything into a single MVC 4 project, but each code solution has different needs and requirements, and even this type of solution can be broken out into multiple projects.

Self-Hosted Web API w/ external Controllers

Let's say you are building an IIS hosted Web API solution. Mainly, all of the clients connecting to your API will be web applications using AJAX. However, your API is also expected to have the ability to expose itself to other .NET clients who may be using the HttpClient object to perform operations. In this case, you may decide to break your solution out into 2 separate projects (I'm simplifying for brevity):
  1. Web Host Project (Empty MVC 4 Project)
  2. API/Service Project (Class Library)
The Web Host Project will be that which actually hosts the service, and the API/Service Project will be the implementation.

I highly recommend taking some time to review the PingYourPackage open source project on GitHub for a reference to such an implementation.

Implementing a Self-Hosted Web API with external assembly dependencies

API Host

Create a Console Application project to host the Web API by following this tutorial: Self-Host a Web API.

Controllers & Service Implementation

Create a new Class Library project for your controllers and service implementation
Implement a controller that inherits ApiController (ProductsController.cs)

Reference AutoFac.WebApi

Add an AutoFac.WebApi reference to your your Class Library project. This can be done via NuGet.

Wire Up AutoFac

You basically have two options here...

1) Add the AutoFac.WebApi dependency registration code to Program.cs.

2) Or, optionally create a configuration class (AutoFacConfig.cs). This will most likely be created in your service implementation project so any host could use it. Be sure to register your controller within this code.

With this, you will be able to call AutoFacConfig.Initialize(config) within your host.

Final Implementation