您需要使用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。
thnx为downvote,如果我失去了一些东西,请关心评论..我已经投入了一些精力和时间来问这些问题。 –