简体   繁体   English

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

[英]How do you do dependency injection with AutoFac and OWIN?

This is for MVC5 and the new pipeline. 这适用于MVC5和新管道。 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. 在尝试切换到OWIN管道之前,这很好用。 Just can't find any information on DI with OWIN. 在OWIN上找不到关于DI的任何信息。

Update: There's an official Autofac OWIN nuget package and a page with some docs . 更新:有一个官方的Autofac OWIN nuget包一个包含一些文档的页面

Original: 原版的:
There's a project that solves the problem of IoC and OWIN integration called DotNetDoodle.Owin.Dependencies available through NuGet . 有一个项目解决了通过NuGet提供的名为DotNetDoodle.Owin.Dependencies的IoC和OWIN集成问题。 Basically Owin.Dependencies is an IoC container adapter into OWIN pipeline. 基本上Owin.Dependencies是进入OWIN管道的IoC容器适配器。

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. 其中RandomTextMiddleware是从Microsoft.Owin实现的OwinMiddleware类。

"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." “将在每个请求上调用OwinMiddleware类的Invoke方法,我们可以决定是否处理请求,将请求传递给下一个中间件或执行两者.Convoke方法获取IOwinContext实例,我们可以到达通过IOwinContext实例的每请求依赖范围。“

Sample code of RandomTextMiddleware looks like: 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);
        }
    }
}

For more information take a look at the original article . 有关更多信息,请查看原始文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM