如何配置 AutoFac,以便每次访问工厂时都能获得一个新的 Context
实例。 Content
组件设置为 InstancePerLifetimeScope()
,这非常适合我 99% 的使用,但现在我需要对 Context< 的使用方式进行一些额外的控制
组件是有作用域的。
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Box>();
builder.RegisterType<DbContext>().InstancePerLifetimeScope();
var container = builder.Build();
using (var scope = container.BeginLifetimeScope())
{
var x = scope.Resolve<Box>();
}
Console.ReadKey();
}
}
class Box
{
public Box(DbContext.Factory factory)
{
factory();
factory(); // Want this to generate a NEW instance
Console.WriteLine("Box: {0}", GetHashCode());
}
}
class DbContext
{
public delegate DbContext Factory();
public DbContext()
{
Console.WriteLine("Context: {0}", GetHashCode());
}
}
显然,这是一段相当简化的代码片段。我试图解决的问题是,我有大量数据进入服务,并且我正在尝试批量保存到数据库。因此,如果 Box
可以根据需要创建新的 UOW,并及时释放它们以供处置,那么我就得到了一个很好的干净解决方案。
谢谢!
最佳答案
您可以使用Func<Owned<>>
它的工作原理就像一个小ILifetimeScope
:
public Box(Func<Owned<DbContext>> factory)
{
using (Owned<DbContext> ownedDbContext = factory())
{
// instance1
}
using (Owned<DbContext> ownedDbContext = factory())
{
// instance2
}
}
您可以在 Autofac 文档中找到更多详细信息:Owned Instances
另一个解决方案是注入(inject) ILifetimeScope
然后创建一个子生命周期范围:
public Box(ILifetimeScope scope)
{
using (ILifetimeScope subScope = scope.BeginLifetimeScope())
{
DbContext dbContext = subScope.Resolve<DbContext>();
}
}
或
public Box(ILifetimeScope scope)
{
ILifetimeScope subScope = scope.BeginLifetimeScope();
scope.Disposer.AddInstanceForDisposal(subScope);
DbContext dbContext = subScope.Resolve<DbContext>();
// no need to dispose subScope,
// subScope (and dbContext) will be disposed at the same time as scope
}
关于c# - 使用工厂时覆盖 AutoFac 范围配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989777/