簡體   English   中英

你如何使用AutoFac和OWIN進行依賴注入?

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

這適用於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的任何信息。

更新:有一個官方的Autofac OWIN nuget包一個包含一些文檔的頁面

原版的:
有一個項目解決了通過NuGet提供的名為DotNetDoodle.Owin.Dependencies的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方法,我們可以決定是否處理請求,將請求傳遞給下一個中間件或執行兩者.Convoke方法獲取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);
        }
    }
}

有關更多信息,請查看原始文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM