加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:02:19 所属栏目:百科 来源:网络整理
导读:这是为MVC5和新的管道.我无法找到一个很好的例子. public static void ConfigureIoc(IAppBuilder app){ var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(WebApiApplication).Assembly); builder.RegisterApiControllers(typeof(W
这是为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 package和 a 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读