您需要将Unit of Work 和Repository 模式与StructureMap 或Unity 等依赖注入框架一起使用。
基本上,你需要做的就是创建接口:
public interface IUnitOfWork
{
void SaveChanges();
}
public interface IRepository<TItem>
{
TItem GetByKey<TKey>();
IQueryable<TItem> Query();
}
现在,在您的 DbContext 类中实现上面的接口,并在您的业务层的某处注册接口的实现:
public void RegisterDependencies(Container container)
{
// Container is a Structure Map container.
container.ForRequestedType<IUnitOfWork>()
.CacheBy(InstanceScope.HttpContext)
.TheDefaultConcreteType<DbContext>();
}
请参阅StructureMap Scoping Docs,了解如何配置实例的范围。
现在,有了所有这些代码,需要执行一些数据操作的每个 Business Layer 类将如下所示:
public class SomeService
{
public SomeService(IRepository<SomeItem> repository, IUnitOfWork unitOfWork)
{
this.repository = repository;
this.unitOfWork = unitOfWork;
}
public void MarkItemCompleted(int itemId)
{
var item = repository.GetByKey(itemId);
if(item != null)
{
item.Completed = true;
unitOfWork.SaveChanges();
}
}
}
现在,将服务的创建隐藏在工厂后面:
public class ServiceFactory
{
private readonly Container container;// = initialize the container
public TService CreateService<TService>()
{
return container.GetInstance<TService>();
}
}
并且在您的 GUI 层中,仅调用通过 ServiceFactory 创建的服务类的方法;如果您的 GUI 是 ASP.NET MVC 项目,则不需要创建 ServiceFactory 类 - 您可以从 DefaultControllerFactory 派生并覆盖 GetControllerInstance 方法。示例见the answer here。