c# – 如何使用AutoFac和OWIN进行依赖注入?

前端之家收集整理的这篇文章主要介绍了c# – 如何使用AutoFac和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管道之前,这很好.只是找不到任何关于DI与OWIN的信息.

解决方法

更新:有一个官方Autofac OWIN nuget packagea page with some docs.

原版的:
有一个项目解决了通过NuGet可用的IoC和OWIN集成称为DotNetDoodle.Owin.Dependencies的问题.基本上,Owin.Dependencies是一个IoC容器适配器到OWIN管道中.

启动代码示例如下所示:

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类的.

“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.”

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.

猜你在找的C#相关文章