您需要使用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,如果我失去了一些東西,請關心評論..我已經投入了一些精力和時間來問這些問題。 –