【问题标题】:Autofac Scoping when Singleton Scoped Object resolves from ComponentContext当 Singleton Scoped Object 从 ComponentContext 解析时 Autofac 作用域
【发布时间】:2016-04-25 20:16:54
【问题描述】:

我们在使用 Autofac 进行范围界定时遇到了一个基本问题。在我们的场景中,我们有一些单例范围的存储库。这些存储库被注入了一个 IDbContextProvider(也是单例范围的)。 IDbContextProvider 只是注入的 Autofac IComponentContext 的包装器。当需要 DbContext 时,存储库会从 DBContextProvider 请求它。 DbContext 的范围为“lifetimescope”,基本上是每个请求,因为这是一个 Web Api。

所以这个想法是存储库可以是单例范围的,因为它们并不多,并且 DBContext 的范围由 Autofac 作为“每个请求”进行管理。这依赖于 Autofac ComponentContext 应该理解它当前所在的“叶”上下文并返回正确的 DbContext 的前提。一位提出此策略的同事告诉我,这是 StructurMap(显然是不同的产品)所表现出的行为。对我来说,Autofac 将解析当前的“叶”上下文并返回正确的 DbContext 是有道理的,但是我们看到 DbContext 存在并发问题,这让我得出结论,IComponentContext 被固定到拥有它的单例上并且是因此返回相同的 DbContext 实例。

//This is singleton scoped
public class DbContextProvider : IDbContextProvider
{

    private readonly IComponentContext _componentContext;

    public DbContextProvider(IComponentContext componentContext)
    {
        _componentContext = componentContext;
    }

    public TDbContext GetDbContext<TDbContext>() where TDbContext : IDbContext
    {
        //DbContext is scoped PerLifetimeScope but the component context
        //appears to only understand the context of the singleton that owns 
        //it and returns the same instance no matter the overall context
        //under which is is requested.
        return _componentContext.Resolve<TDbContext>();
    }

}

有没有办法完成我们在这里的目标,或者是将整个依赖树限定为 PerLifetimeScope 以获得正确行为的唯一行动方案。

谢谢...

【问题讨论】:

    标签: asp.net autofac


    【解决方案1】:

    IComponentContext 用相关生命周期解析,但相关生命周期在这里是单例的,所以会在容器中解析。你应该使用DependencyResolver.Current.GetService

    public class DbContextProvider : IDbContextProvider
    {
    
    
        public DbContextProvider()
        {
    
        }
    
        public TDbContext GetDbContext<TDbContext>() where TDbContext : IDbContext
        {
            //DbContext is scoped PerLifetimeScope but the component context
            //appears to only understand the context of the singleton that owns 
            //it and returns the same instance no matter the overall context
            //under which is is requested.
            return DependencyResolver.Current.GetService.Resolve<TDbContext>();
        }
    
    }
    

    您也可以查看article

    【讨论】:

    • 这不取决于有可用的 HTTP 上下文吗?此功能在 web api 和非 web 事件处理程序之间重用,因此依赖于需要 HttpContext 的东西是行不通的。
    • Hımm 在 web api 当前生命周期是 http 请求。但是在非网络中,您是否在解决顶部问题之前创建了生命周期?如果您创建,我将测试并编辑我的答案以同时使用两者。如果您不开始新的生命周期并直接从容器中解析,我认为您无法实现这一点。
    猜你喜欢
    • 2020-08-23
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2018-05-02
    • 2014-07-31
    相关资源
    最近更新 更多