gpt4 book ai didi

c# - unity PerThreadLifetimeManager 和任务

转载 作者:太空狗 更新时间:2023-10-29 21:34:19 25 4
gpt4 key购买 nike

我正在使用 EntityFramework 并在一堆后台作业类中实现通用存储库和工作单元模式。作业类是使用 Unity DI 创建的,因此它们可以注入(inject)依赖项,这些依赖项主要是存储库和 UnitOfWork 对象。存储库和工作单元应共享 EF DbContext

一个常见的工作看起来像这样:

public class CommonJob : IJob, IDisposable
{
private IRepo<SomeEntity> _repo;
private IUnitOfWork _uow;

public CommonJob(IRepo<SomeEntity> repo, IUnitOfWork uow)
{
_repo = repo;
_uow = uow;
}

public void RunJob()
{
// do stuff here
}

public void Dispose()
{
_uow.Commit();
_uow.Dispose();
}
}

所有作业都在新任务中运行,像这样

Task.Factory.StartNew(() => {
// container is UnityContainer
var job = container.Resolve<CommonJob>();
job.RunJob();
job.Dispose();
});

而且我已经使用 PerThreadLifetimeManager 向 Unity 注册了工作单元和存储库,认为这将允许在一个任务的上下文中共享已注册的实例(并且在那个作业中对象),但不在外部。

我遇到的问题是有时作业会注入(inject)已处置的对象,这显然不是很好。我一直在阅读 Task.Factory.StartNew() 并不总是使用新线程。这是否意味着 PerThreadLifetimeManager 将在任务之间共享对象?如果这是真的,是否有另一种统一管理对象生命周期的方法,这将允许每个任务独立工作,而不管它在哪个线程上运行?

编辑:

虽然下面选择的答案将实现相同的目的,但我最终使用 HierarchicalLifetimeManager 和子容器来实现每个作业的依赖项隔离。

这是一个例子:

// registering the dependencies, 
// these should be singletons, but only within the context of one job
_container.Register(typeof(IRepo<>), typeof(Repo<>), new HierarchicalLifetimeManager())
.Register<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());

// starting a new job
Task.Factory.StartNew<IUnityContainer>(() =>
{
// create a child container to remove instance sharing between tasks
var childContainer = _container.CreateChildContainer();

// figure out and resolve the job class from the child container
// this will make sure that different jobs do not share instances
var jobType = GetJobType();
var job = childContainer.Resolve(jobType) as IJob;

job.RunJob();

return childContainer;
}).ContinueWith(previousTask => {
// when the job is done, dispose of the child container
task.Result.Dispose();
});

最佳答案

因为并行库使用线程池,Unity 会为池中的同一个线程返回同一个对象。

如果按照你发布的方式使用容器,我建议你使用PerResolveLifetimeManager .这样,当您解析一个对象时,整个解析图共享同一个实例,但每个解析的实例都是唯一的:每个任务在调用 Resolve 时都会有自己的实例。

关于c# - unity PerThreadLifetimeManager 和任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18308842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com