Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 965
Shane Avatar asked Nov 19 '13 00:11

Shane


People also ask

What is Autofac dependency injection?

Autofac is an open-source dependency injection (DI) or inversion of control (IoC) container developed on Google Code. Autofac differs from many related technologies in that it sticks as close to bare-metal C# programming as possible.

How Autofac is implemented in MVC?

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.


1 Answers

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.

like image 141
Alexandr Nikitin Avatar answered Sep 19 '22 05:09

Alexandr Nikitin