Shane
Shane

Reputation: 4315

How do you do dependency injection with AutoFac and OWIN?

This is for MVC5 and the new pipeline. I cannot find a good example anywhere.

public static void ConfigureIoc(IAppBuilder app)
{
    var builder = new ContainerBuilder();
    builder.RegisterControllers(typeof(WebApiApplication).Assembly);
    builder.RegisterApiControllers(typeof(WebApiApplication).Assembly);
    builder.RegisterType<SecurityService().AsImplementedInterfaces().InstancePerApiRequest().InstancePerHttpRequest();

    var container = builder.Build();
    app.UseAutofacContainer(container);
}

The above code doesn't inject. This worked fine before attempting to switch to OWIN pipeline. Just can't find any information on DI with OWIN.

Upvotes: 16

Views: 18986

Answers (1)

Alexandr Nikitin
Alexandr Nikitin

Reputation: 7436

Update: There's an official Autofac OWIN nuget package and a page with some docs.

Original:
There's a project that solves the problem of IoC and OWIN integration called DotNetDoodle.Owin.Dependencies available through NuGet. Basically Owin.Dependencies is an IoC container adapter into OWIN pipeline.

Sample startup code looks like:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        IContainer container = RegisterServices();
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute("DefaultHttpRoute", "api/{controller}");

        app.UseAutofacContainer(container)
           .Use<RandomTextMiddleware>()
           .UseWebApiWithContainer(config);
    }

    public IContainer RegisterServices()
    {
        ContainerBuilder builder = new ContainerBuilder();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        builder.RegisterOwinApplicationContainer();

        builder.RegisterType<Repository>()
               .As<IRepository>()
               .InstancePerLifetimeScope();

        return builder.Build();
    }
}

Where RandomTextMiddleware is implementation of OwinMiddleware class from Microsoft.Owin.

"The Invoke method of the OwinMiddleware class will be invoked on each request and we can decide there whether to handle the request, pass the request to the next middleware or do the both. The Invoke method gets an IOwinContext instance and we can get to the per-request dependency scope through the IOwinContext instance."

Sample code of RandomTextMiddleware looks like:

public class RandomTextMiddleware : OwinMiddleware
{
    public RandomTextMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        IServiceProvider requestContainer = context.Environment.GetRequestContainer();
        IRepository repository = requestContainer.GetService(typeof(IRepository)) as IRepository;

        if (context.Request.Path == "/random")
        {
            await context.Response.WriteAsync(repository.GetRandomText());
        }
        else
        {
            context.Response.Headers.Add("X-Random-Sentence", new[] { repository.GetRandomText() });
            await Next.Invoke(context);
        }
    }
}

For more information take a look at the original article.

Upvotes: 14

Related Questions