微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/csharp/97331.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐