/ mono

Using Autofac with Asp.NET vNext

.Net Core-RC2 has rendered all this information Deprecated.

In Asp.NET vNext, the Startup.cs is a conventions based initialization strategy that the framework uses to setup your application. Today I will enumerate how to use this to provide your own IOC container for automagic dependency activation/initialization and lifetime scope management. If you're fine working directly with the IServiceProvider interface for your poject and think IOC containers are not needed, then this article isn't for you.

Inversion of Control aka IOC is a software design pattern that delegates object creation (and further more lifetime scope) to a 3rd party that's sole responsibility is to perform this function. IOC when used with the overarching patterns expressed by SOLID allows you to create applications that have behavior encapsulated correctly in a modular way.

The conventions based approach here can be disorienting for those that are used to some of the classic ways that asp.net has provided runtime configuration. Just remember to not assume you know how it has to be done, some patterns are very similar, while others are new.

Startup.cs

Reference: ASP.NET overview documentation on Startup.cs

My tutorial uses the yeoman package for asp.net, this makes doing all of the boiler plate framing so much easier. If you already have this dependency, great! If not you can refer to my article for how to get started with asp.net vNext and yeoman Web Api project from yeoman.

Create your project

Go to whichever root directory you want your project to be created under

yo aspnet

Follow the prompts and onscreen instructions for creating a WebApi Project and then initially building it

Adding IOC Pieces

You will need to add the following packages to your project

  • Microsoft.Framework.DependencyInjection
  • Autofac
  • Autofac.Framework.DependencyInjection

From the root of your project (where your package.json file is) run the following command to add the right dependency to your project

dnu install Microsoft.Framework.DependencyInjection
dnu install Autofac
dnu install Autofac.Framework.DependencyInjection

Update Startup.cs

Now you will have all the libraries required. To the fun part of wiring it all together. Just in case your project is slightly different.

Change public void ConfigureServices(IServiceCollection services) to public void IServiceProvider ConfigureServices(IServiceCollection services)

Asp.NET vNext provides an IOC container interface through IServiceProvider. Autofac is so awesome that they have even provided a package to help you wire it all together.

Using Autofac's IServiceProvider

Add these using statements to the top of your Startup.cs

using Autofac;
using Autofac.Framework.DependencyInjection;

Add these lines to ConfigureServices method and remember to change the signature of ConfigureServices to return IServiceProvider

//Create the container builder
var builder = new ContainerBuilder();

// Create the container and use the default application services as a fallback
AutofacRegistration.Populate(builder, services);

// Use the builder to register your interfaced type and set it's instance to LifetimeScope which is by Request
//builder.RegisterType<YourConcreteImplementation>()
//       .As<IYourInterface>()
//       .InstancePerLifetimeScope();
            
//Build the container and then return It's IServiceProvider
var container = builder.Build();
return container.Resolve<IServiceProvider>();
Try it out

All this hand wavy code on a web page sounds good, but lets give it a try to show it all working together

Add Interface to project

I created a folder in my project Middleware/Interfaces to put IWidget.cs in

namespace asp_vnext_ioc.Interfaces
{
	public interface IWidget
	{
		string DoWidgetThings();
	}
}
Add Implementation of Interface IWidget

In the Middleware folder I created WidgetImpl_A.cs yes this name sucks, examples are fun :)

using asp_vnext_ioc.Interfaces;
namespace asp_vnext_ioc
{
    public class WidgetImpl_A : IWidget
    {
        public string DoWidgetThings()
        {
            return "This is my Widget Implementation!";
        }
    }
}
Add a Controller that needs IWidget interface in the constructor
using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
namespace Controllers
{
  [Route("api/[controller]")]
  public class IOCController : Controller
  {
    IWidget _injectedObject;
    public IOCController(IWidget injected) 
    {
      _injectedObject = injected;
    }

    [HttpGet]
    public string Get()
    {
      return _injectedObject.GetType().ToString();			
    }
  }
}
Wire it into Autofac

From the example above open Statup.cs and add this before container.build();

builder.RegisterType<WidgetImpl_A>()
       .As<Interfaces.IWidget>()
       .InstancePerLifetimeScope();

Fire it up and curl it

dnx web
curl http://localhost:5000/api/ioc | jq .
"This is my Widget Implementation!"

Working Code Sample

It's all fine and good if you kinda know what you want and the above info ties it together. If you want to checkout a fully working example of this feel free to clone from my public gitlab repository https://gitlab.com/codedad/aspnet-vnext-ioc-autofac

ASP.NET overview documentation on Startup.cs

ASP.NET detailed documentation on Startup.cs

SOLID

Sample Project Source

Using Autofac with Asp.NET vNext
Share this