嗨,我正在使用 Unity 来管理我的服务层,而后者又与管理所有存储库的 UnitOfWork 对话。
我的一些服务调用其他服务,我的问题是如何在服务层之间传递相同的 UnitOfWork?
在我的情况下,所有控制器操作都是从 GUI 对每个按钮操作或计时器上的事件启动的,这就是为什么我有一个工厂来按需创建 UnitOfWork,但这会导致问题,因为我不知道如何在服务之间传递这个 UnitOfWork .
尤其困难的是知道如何将这个特定的 UnitOfWork 实例注入到服务构造函数中。请注意,某些服务可能运行时间很长(后台线程上运行 10 分钟左右),我不知道这是否对设计有任何影响。
目前,从其他服务调用的服务正在创建自己的 UnitOfWork,这会导致事务设计和实体框架实体跟踪出现问题。
非常欢迎提出建议!
class OtherService : IOtherService
{
public OtherService(IUnitOfWorkFactory unitOfworkFactory,
ISettingsService settingsService)
{
UnitOfWorkFactory = unitOfworkFactory;
SettingsService = settingsService;
}
IUnitOfWorkFactory UnitOfWorkFactory;
ISettingsService SettingsService;
function SomeSeviceCall()
{
// Perhaps one way is to use a factory to instantiate a
// SettingService, and pass in the UnitOfWork here?
// Ideally it would be nice for Unity to handle all of
// the details regardless of a service being called from
// another service or called directly from a controller
// ISettingsService settingsService =
// UnityContainer.Resolve<ISettingService>();
using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
{
var companies = uow.CompaniesRepository.GetAll();
foreach(Company company in companies)
{
settingsService.SaveSettings(company, "value");
company.Processed = DateTime.UtcNow();
}
uow.Save();
}
}
}
class SettingsService : ISettingsService
{
public SettingsService(IUnitOfWorkFactory unitOfworkFactory)
{
UnitOfWorkFactory = unitOfworkFactory;
}
IUnitOfWorkFactory UnitOfWorkFactory;
// ISettingsService.SaveSettings code in another module...
function void ISettingsService.SaveSettings(Company company,
string value)
{
// this is causing an issue as it essentially creates a
// sub-transaction with the new UnitOfWork creating a new
// Entiy Framework context
using (var uow = UnitOfWorkFactory.CreateUnitOfWork())
{
Setting setting = new Setting();
setting.CompanyID = company.CompanyID;
setting.SettingValue = value;
uow.Insert(setting);
uow.Save();
}
}
}