【发布时间】: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 以获得正确行为的唯一行动方案。
谢谢...
【问题讨论】: