[英]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.