你如何使用AutoFac和OWIN进行依赖注入?

时间:2013-11-19 00:52:43

标签: c# dependency-injection asp.net-mvc-5 owin autofac

这适用于MVC5和新管道。我无法在任何地方找到一个好的例子。

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);
}

上面的代码没有注入。在尝试切换到OWIN管道之前,这很好用。在OWIN上找不到关于DI的任何信息。

1 个答案:

答案 0 :(得分:11)

更新:有正式的Autofac OWIN nuget packagea page with some docs

<强>原始
有一个项目通过DotNetDoodle.Owin.Dependencies解决了名为NuGet的IoC和OWIN集成问题。基本上Owin.Dependencies是进入OWIN管道的IoC容器适配器。

示例启动代码如下所示:

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();
    }
}

其中RandomTextMiddleware是来自Microsoft.Owin的OwinMiddleware类的实现。

  

“将在每个请求上调用OwinMiddleware类的Invoke方法,我们可以决定是否处理请求,将请求传递给下一个中间件或两者兼而有之.Invoke方法获取一个IOwinContext实例,我们可以通过IOwinContext实例获取每请求依赖项范围。“

RandomTextMiddleware的示例代码如下:

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);
        }
    }
}

有关详细信息,请查看original article