在我的应用程序中,我需要与两个数据库进行交互。我有两个域类位于两个不同的数据库中。我也有一个通用的存储库模式,它的构造函数接受一个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