Skip to content

autofac/Autofac.Mvc.Owin

Repository files navigation

Autofac.Mvc.Owin

OWIN support for the ASP.NET MVC integration for Autofac.

Build status

Please file issues and pull requests for this package in this repository rather than in the Autofac core repo.

If you're working with ASP.NET Core, you want Autofac.Extensions.DependencyInjection, not this package.

Quick Start

If you are using MVC as part of an OWIN application, you need to:

public class Startup
{
  public void Configuration(IAppBuilder app)
  {
    var builder = new ContainerBuilder();

    // STANDARD MVC SETUP:

    // Register your MVC controllers.
    builder.RegisterControllers(typeof(MvcApplication).Assembly);

    // Run other optional steps, like registering model binders,
    // web abstractions, etc., then set the dependency resolver
    // to be Autofac.
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

    // OWIN MVC SETUP:

    // Register the Autofac middleware FIRST, then the Autofac MVC middleware.
    app.UseAutofacMiddleware(container);
    app.UseAutofacMvc();
  }
}

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.

Check out the Autofac ASP.NET MVC integration documentation for more information.

Get Help

Need help with Autofac? We have a documentation site as well as API documentation. We're ready to answer your questions on Stack Overflow or check out the discussion forum.