在我的應用程序中,我需要與兩個數據庫進行交互。我有兩個域類位於兩個不同的數據庫中。我也有一個通用的存儲庫模式,它的構造函數接受一個UoW。我正在尋找一種方法來基於Domain類注入適當的UoW。 我不想爲第二個數據庫編寫第二個通用存儲庫。。有沒有簡潔的解決方案?根據域類將不同的DbContext注入到通用存儲庫中 - Autofac
public interface IEntity
{
int Id { get; set; }
}
位於數據庫A
public class Team: IEntity
{
public int Id { get; set; }
public string Name{ get; set; }
}
位於數據庫B
public class Player: IEntity
{
public int Id { get; set; }
public string FullName { get; set; }
}
我也有一個通用的存儲庫模式與UOW
public interface IUnitOfWork
{
IList<IEntity> Set<T>();
void SaveChanges();
}
public class DbADbContext : IUnitOfWork
{
public IList<IEntity> Set<T>()
{
return new IEntity[] { new User() { Id = 10, FullName = "Eric Cantona" } };
}
public void SaveChanges()
{
}
}
public class DbBDataContext: IUnitOfWork
{
public IList<IEntity> Set<T>()
{
return new IEntity[] { new Tender() { Id = 1, Title = "Manchester United" } };
}
public void SaveChanges()
{
}
public interface IRepository<TEntity> where TEntity: class, IEntity
{
IList<IEntity> Table();
}
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class, IEntity
{
protected readonly IUnitOfWork Context;
public BaseRepository(IUnitOfWork context)
{
Context = context;
}
IList<IEntity> IRepository<TEntity>.Table()
{
return Context.Set<TEntity>();
}
}
我已經找到文章說Autofac覆蓋了最後一個值的註冊。我知道我的問題是如何註冊DbContexts。
var builder = new ContainerBuilder();
// problem is here
builder.RegisterType<DbADbContext >().As<IUnitOfWork>()
builder.RegisterType<DbBDbContext >().As<IUnitOfWork>()
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IRepository<>));
var container = builder.Build();
它不會工作,第一個不符合我的觀點。 第二個也不是解決方案,因爲解決方案應取決於存儲庫中的「TEntity」的類型 有關命名和元數據的更多信息,請參見此處 http://docs.autofac.org/zh/latest/ faq/select-by-context.html#option-4-use-metadata – Mahdi