有一個關於這個有很多意見,但我這是怎麼算出來爲自己
的UnitOfWork
public interface IUnitOfWork : IDisposable
{
FooContext DbContext { get; }
void Save();
}
public class UnitOfWork : IUnitOfWork
{
protected string ConnectionString;
private FooContext context;
public UnitOfWork(string connectionString)
{
this.ConnectionString = connectionString;
}
public FooContext DbContext
{
get
{
if (context == null)
{
context = new FooContext(ConnectionString);
}
return context;
}
}
...
}
GenericRepository這裏
public class GenericRepository<TEntity> :
IGenericRepository<TEntity> where TEntity : class
{
protected FooContext DbContext;
public GenericRepository(IUnitOfWork unitOfWork)
{
this.DbContext = unitOfWork.DbContext;
}
...
}
通用庫,但他們可以同樣也要建立具體的。
服務
public class FooService : IFooService
{
private IUnitOfWork unitOfWork;
private IGenericRepository<Foo> fooRepository;
private IGenericRepository<Bar> barRepository;
public FooService(IUnitOfWork unitOfWork,
IGenericRepository<Foo> fooRepository,
IGenericRepository<Bar> barRepository)
{
this.unitOfWork = unitOfWork;
this.fooRepository = fooRepository;
this.barRepository = barRepository;
}
}
您仍然需要通過IUnitOfWork獲得訪問Save
方法。我想我可以從其中一個倉庫獲得它。
UnityConfig
var container = new UnityContainer();
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager(),
new InjectionConstructor(ConnectionString));
container.RegisterType(typeof(IGenericRepository<>), typeof(GenericRepository<>));
container.RegisterType<IFooService, FooService>();
container.RegisterType<IBarService, BarService>();
控制器
private IFooService fooService;
private IBarSevice barService;
public HomeController(IFooService fooService, IBarService barService)
{
this.fooService = fooService;
this.barService = barService;
}
因此,這將自動注入的UnitOfWork到服務和資源庫? – user1790300
@ user1790300是的,因爲鏈中的每個依賴性註冊 – Jasen
這將是工作單位的便利,使倉庫的性能(與延遲加載)。所以,你需要傳遞一個工作單元而不需要很長的存儲庫列表。 – eternity