目前,我将工作单元的单个实例注入到我的控制器中的服务层对象中:
public class OrderController : Controller
{
private IUnitOfWork _unitOfWork;
private IOrderService _recipeService;
private IInventoryService _inventoryService;
public OrderController(IUnitOfWork unitOfWork, IOrderService orderService, IInventoryService inventoryService)
{
_unitOfWork = unitOfWork;
_orderService = orderService;
_inventoryService = inventoryService
//Use property injection to apply the Unit of Work context and validation state to our services
_orderService.Context = _unitOfWork;
_inventoryService.Context = _unitOfWork;
}
理想情况下,我想从控制器中删除 UoW 上下文,并在注册期间定义 UoW 的生命周期,以便在 HTTP 请求的范围内使用相同的 UoW。在请求期间实例化的每个服务对象都将具有通过 Unity 注入的相同实例 UoW。我也想在我的控制器中使用异步操作,我不确定那里是否有任何影响。
HierarchicalLifetimeManager 的描述听起来像我想要的,但我想 110% 确定,因为我认为如果我弄错了,我最终可能会陷入调试噩梦(参考:http ://unitymvc3.codeplex.com/ )
以下注册是否会为我提供所需的行为,还是应该以另一种方式处理?
container.RegisterType<IOrderService, OrderService>();
container.RegisterType<IInventoryService, InventoryService>();
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
谢谢!
克里斯