Autofac is always kept up to date to support the latest version of ASP.NET MVC, so documentation is also kept up with the latest. Generally speaking, the integration remains fairly consistent across versions.

To get Autofac integrated with MVC you need to reference the MVC integration NuGet package, register your controllers, and set the dependency resolver. You can optionally enable other features as well.

At application startup, while building your Autofac container, you should register your MVC controllers and their dependencies. This typically happens in an OWIN startup class or in the Application_Start method in Global.asax.

varbuilder=newContainerBuilder();// You can register controllers all at once using assembly scanning...builder.RegisterControllers(typeof(MvcApplication).Assembly);// ...or you can register individual controlllers manually.builder.RegisterType<HomeController>().InstancePerRequest();

Note that ASP.NET MVC requests controllers by their concrete types, so registering them As<IController>() is incorrect. Also, if you register controllers manually and choose to specify lifetimes, you must register them as InstancePerDependency() or InstancePerRequest() - ASP.NET MVC will throw an exception if you try to reuse a controller instance for multiple requests.

After building your container pass it into a new instance of the AutofacDependencyResolver class. Use the static DependencyResolver.SetResolver method to let ASP.NET MVC know that it should locate services using the AutofacDependencyResolver. This is Autofac’s implementation of the IDependencyResolver interface.

An optional step you can take is to enable dependency injection for model binders. Similar to controllers, model binders (classes that implement IModelBinder) can be registered in the container at application startup. You can do this with the RegisterModelBinders() method. You must also remember to register the AutofacModelBinderProvider using the RegisterModelBinderProvider() extension method. This is Autofac’s implementation of the IModelBinderProvider interface.

Because the RegisterModelBinders() extension method uses assembly scanning to add the model binders you need to specify what type(s) the model binders (IModelBinder implementations) are to be registered for.

This is done by using the Autofac.Integration.Mvc.ModelBinderTypeAttribute, like so:

The MVC integration includes an Autofac module that will add HTTP request lifetime scoped registrations for the web abstraction classes. This will allow you to put the web abstraction as a dependency in your class and get the correct value injected at runtime.

The following abstract classes are included:

HttpContextBase

HttpRequestBase

HttpResponseBase

HttpServerUtilityBase

HttpSessionStateBase

HttpApplicationStateBase

HttpBrowserCapabilitiesBase

HttpFileCollectionBase

RequestContext

HttpCachePolicyBase

VirtualPathProvider

UrlHelper

To use these abstractions add the AutofacWebTypesModule to the container using the standard RegisterModule() method.

To make use of property injection for your filter attributes call the RegisterFilterProvider() method on the ContainerBuilder before building your container and providing it to the AutofacDependencyResolver.

builder.RegisterFilterProvider();

This allows you to add properties to your filter attributes and any matching dependencies that are registered in the container will be injected into the properties.

For example, the action filter below will have the ILogger instance injected from the container (assuming you register an ILogger. Note that the attribute itself does not need to be registered in the container.

While not common, some folks want to have Autofac populate parameters in action methods when they’re called. It is recommended you use constructor injection on your controller rather than action method injection but you can enable action method injection if you desire:

// The Autofac ExtensibleActionInvoker attempts to resolve parameters// from the request lifetime scope IF the model binder can't bind// to the parameter.builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();builder.InjectActionInvoker();

Note you can use the InjectActionInvoker() mechanism with your own custom invoker, too.

Minor gotcha: MVC doesn’t run 100% in the OWIN pipeline. It still needs HttpContext.Current and some other non-OWIN things. At application startup, when MVC registers routes, it instantiates an IControllerFactory that ends up creating two request lifetime scopes. It only happens during app startup at route registration time, not once requests start getting handled, but it’s something to be aware of. This is an artifact of the two pipelines being mangled together. We looked into ways to try working around it but were unable to do so in a clean fashion.

If you choose configuration, you need to add your plugin assembly to the /configuration/system.web/compilation/assemblies list. If your plugin assembly isn’t in the bin folder, you also need to update the /configuration/runtime/assemblyBinding/probing path.

<?xml version="1.0" encoding="utf-8"?><configuration><runtime><assemblyBindingxmlns="urn:schemas-microsoft-com:asm.v1"><!-- If you put your plugin in a folder that isn't bin, add it to the probing path --><probingprivatePath="bin;bin\plugins"/></assemblyBinding></runtime><system.web><compilation><assemblies><addassembly="The.Name.Of.Your.Plugin.Assembly.Here"/></assemblies></compilation></system.web></configuration>

If you choose programmatic registration, you need to do it during pre-application-start before the ASP.NET BuildManager kicks in.

Create an initializer class to do the assembly scanning/loading and registration with the BuildManager:

Once you set the MVC DependencyResolver to an AutofacDependencyResolver, you can use AutofacDependencyResolver.Current as a shortcut to getting the current dependency resolver and casting it to an AutofacDependencyResolver.

Unfortunately, there are some gotchas around the use of AutofacDependencyResolver.Current that can result in things not working quite right. Usually these issues arise by using a product like Glimpse or Castle DynamicProxy that “wrap” or “decorate” the dependency resolver to add functionality. If the current dependency resolver is decorated or otherwise wrapped/proxied, you can’t cast it to AutofacDependencyResolver and there’s no single way to “unwrap it” or get to the actual resolver.

Prior to version 3.3.3 of the Autofac MVC integration, we tracked the current dependency resolver by dynamically adding it to the request lifetime scope. This got us around issues where we couldn’t unwrap the AutofacDependencyResolver from a proxy… but it meant that AutofacDependencyResolver.Current would only work during a request lifetime - you couldn’t use it in background tasks or at application startup.

Starting with version 3.3.3, the logic for locating AutofacDependencyResolver.Current changed to first attempt to cast the current dependency resolver; then to specifically look for signs it was wrapped using Castle DynamicProxy and unwrap it via reflection. Failing that… we can’t find the current AutofacDependencyResolver so we throw an InvalidOperationException with a message like:

The dependency resolver is of type ‘Some.Other.DependencyResolver’ but was expected to be of type ‘Autofac.Integration.Mvc.AutofacDependencyResolver’. It also does not appear to be wrapped using DynamicProxy from the Castle Project. This issue could be the result of a change in the DynamicProxy implementation or the use of a different proxy library to wrap the dependency resolver.

The typical place where this is seen is when using the action filter provider via ContainerBuilder.RegisterFilterProvider(). The filter provider needs to access the Autofac dependency resolver and uses AutofacDependencyResolver.Current to do it.

If you see this, it means you’re decorating the resolver in a way that can’t be unwrapped and functions that rely on AutofacDependencyResolver.Current will fail. The current solution is to not decorate the dependency resolver.

Integration of an MVC application with Glimpse when using Autofac is pretty much the same as with any other integration. However, if you use action method parameter injection (e.g., with builder.InjectActionInvoker()) then Glimpse execution inspection will fail.

You can work around this by adding the following to your Glimpse configuration:

Again, you only need to do this if you’re using the action parameter injection. This is one of the many reasons it’s recommended to use controller constructor injection instead of action method parameter injection.

For more info on why this is (including links to the associated info from Glimpse), check out this issue.

When unit testing an ASP.NET MVC app that uses Autofac where you have InstancePerRequest components registered, you’ll get an exception when you try to resolve those components because there’s no HTTP request lifetime during a unit test.