Sha*_*ane 11 c# dependency-injection autofac owin asp.net-mvc-5
这适用于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);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没有注入.在尝试切换到OWIN管道之前,这很好用.在OWIN上找不到关于DI的任何信息.
Ale*_*tin 11
更新:有一个官方的Autofac OWIN nuget包和一个包含一些文档的页面.
原文:
有,解决了国际奥委会和OWIN集成称为问题项目DotNetDoodle.Owin.Dependencies可通过的NuGet.基本上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();
}
}
Run Code Online (Sandbox Code Playgroud)
哪里RandomTextMiddleware是实现OwinMiddleware从Microsoft.Owin类.
"在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看原始文章.