配置Autofac的容器后台线程 [英] Configure Autofac Container for background thread

查看:487
本文介绍了配置Autofac的容器后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多组件使用InstancePerHtt prequest范围注册一个asp.net MVC的网站,但是我也有一个后台任务,这将运行,不会有一个HttpContext的每隔几个小时。

I have an asp.net MVC site which has many components registered using an InstancePerHttpRequest scope, however I also have a "background task" which will run every few hours which will not have an httpcontext.

我想获得已注册这样我IRepository的实例

I would like to get an instance of my IRepository which has been registered like this

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
     .InstancePerHttpRequest();

我如何做到这一点从使用Autofac非HTTP上下文?我认为IRepository应该使用InstancePerLifetimeScope

How do I do this from a non http context using Autofac? I think the IRepository should use the InstancePerLifetimeScope

推荐答案

有你如何能做到这几个方面:

There are several ways of how you can do that:


  1. 在我看来,最好的一个。如你所说,你可以注册存储库中InstancePerLifetimeScope。它的工作原理与Htt的prequests和LifetimeScopes同样出色。

  1. The best one in my opinion. You can register the repository as InstancePerLifetimeScope as you said. It works with HttpRequests and LifetimeScopes equally well.

builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
    .InstancePerLifetimeScope();


  • 您对Htt的prequest登记可从注册差异,LifetimeScope,那么你可以有两个单独的注册:

  • Your registration for HttpRequest may differ from registration for LifetimeScope, then you can have two separate registrations:

    builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
        .WithParameter(...)
        .InstancePerHttpRequest(); // will be resolved per HttpRequest
    
    builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
        .InstancePerLifetimeScope(); // will be resolved per LifetimeScope
    


  • 您可以明确创建使用其标记的Htt prequest范围。在新的版本通过 MatchingScopeLifetimeTags.RequestLifetimeScopeTag 公开的属性。

  • You can explicitly create "HttpRequest" scope using its tag. Exposed through MatchingScopeLifetimeTags.RequestLifetimeScopeTag property in new versions.

    using (var httpRequestScope = container.BeginLifetimeScope("httpRequest")) // or "AutofacWebRequest" for MVC4/5 integrations
    {
        var repository = httpRequestScope.Resolve<IRepository<Entity>>();
    }
    


  • 这篇关于配置Autofac的容器后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆