我正在使用带有 POCO 类的统一实体框架 4、用于 DAL 的存储库模式和用于业务逻辑控制的服务。我还想使用工作单元,这样我就可以将我在不同服务上执行的 CRUD 操作打包在一起,然后将它们一起提交。
我的问题是使用 Microsoft Unity 将工作单元机制注入我的应用程序的正确方法是什么?我知道我可以将 IUnitOfWork 与适当服务的构造函数上的存储库放在一起,然后如果指定 Unity 映射,它将自动启动适当的实例,但这样我不会传递全局工作单元而是创建一个每个级别上的新实例,这不是一个聪明的方法(实际上存储库甚至在服务之前启动)。
我错过了什么?(附件是我现在编写的服务及其存储库的构造函数代码)。
你也明白我可以使用 Unity 的 ParameterOverrides 方法获取工作单元的一些全局实例(比如说从我的 aspx.cs 文件中)并将其传递到服务中,然后传递到存储库中。但这似乎有点蹩脚。这是我唯一的选择吗?
谢谢
public class GenericRepository<T> : IUnitOfWorkRepository, IGenericRepository<T> where T : BaseEntity, IAggregateRoot
{
private IUnitOfWork _uow;
/// <summary>
/// Returns the active object context
/// </summary>
private ObjectContext ObjectContext
{
get
{
return ObjectContextManager.GetObjectContext();
}
}
public GenericRepository(IUnitOfWork uow)
{
_uow = uow;
}
//blahhhh...
public void Add(T entity)
{
_uow.RegisterNew(entity, this);
}
public void Delete(T entity)
{
_uow.RegisterRemoved(entity, this);
}
//.....blah blah....
public void PersistCreationOf(IAggregateRoot entity)
{
this.ObjectContext.AddObject(GetEntitySetName(), entity);
}
public void PersistUpdateOf(IAggregateRoot entity)
{
// Do nothing as EF tracks changes
}
public void PersistDeletionOf(IAggregateRoot entity)
{
this.ObjectContext.DeleteObject(entity);
}
}
public class CategoryRepository : GenericRepository<XComSolutions.FB.Domain.Model.Entities.Category>, ICategoryRepository
{
public CategoryRepository(IUnitOfWork uow)
: base(uow)
{ }
}
public class CategoryService : ICategoryService
{
public int myID {get; set;}
private ICategoryRepository _categoryRepository;
private IUnitOfWork _uow;
public CategoryService(ICategoryRepository categoryRepository,
IUnitOfWork uow)
{
_categoryRepository = categoryRepository;
_uow = uow;
}
public List<Category> GetAll()
{
return _categoryRepository.GetAll();
}
}