ASP.NET 5 Dependency Injection – Bring Your Own Container

The default DI container that comes with ASP.NET 5 is basic, and doesn’t support all of the features found in third-party containers. In this post we’ll see how to replace the default container with StructureMap and Autofac. Keep in mind that the ASP.NET 5 integration for these containers were only recently released and may still be under development. As such, features may not be implemented yet, especially when targeting Core CLR.

StructureMap

Integrating StructureMap in ASP.NET 5 is extremely easy, and we will modify the example from the last post to use StructureMap. We add StructureMap to the dependencies listed in project.json:

We add registry classes:

In the Startup class, we need to modify the ConfigureServices method to return an IServiceProvider, create a StructureMap Container, populate it, and use it to return an IServiceProvider:

Those are all of the changes required; the rest of the application is the same as when using the default container.

Running the application, browsing to the site and then refreshing, we see the following results:

structuremap-0

structuremap-1

You can download the source code for this example here:

Autofac

Substituting Autofac in is just as easy. We modify the project.json file to include Autofac:

We add module classes:

In the Startup class, we modify ConfigureServices to return IServiceProvider, configure an Autofac container and use it to return an IServiceProvider.

These are all of the changes needed to use Autofac. Running the application with Autofac and refreshing the page, we see the following results:

autofac-0

autofac-1

You can download the source code for this example here:

Leave a Reply