我有一个项目,我的项目连接到两个不同的数据库,即BookStoreEntities和BlogEntities。
如果我在Autofac配置中删除行代码builder.RegisterType<BlogEntities>().As<DbContext>();
,我的项目就可以正常工作,否则我会得到错误"实体类型Book不是当前上下文模型的一部分"。
我的autofac配置:
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<BookStoreEntities>().As<DbContext>();
builder.RegisterType<BlogEntities>().As<DbContext>();
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerDependency();
builder.RegisterType<BookService>().As<IBookService>();
builder.RegisterFilterProvider();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
存储库类:
public class Repository<T> : IRepository<T> where T : class
{
private DbContext _dbContext;
private DbSet<T> _dbSet;
public Repository(DbContext dbContext)
{
_dbContext = dbContext;
_dbSet = dbContext.Set<T>();
}
public IEnumerable<T> GetAll()
{
return _dbSet;
}
}
服务层:
public class BookService : IBookService
{
private IRepository<Book> _bookRepository;
public BookService(IRepository<Book> bookRepository)
{
_bookRepository = bookRepository;
}
public IEnumerable<Book> GetBooks()
{
return _bookRepository.GetAll();
}
}
控制器:
public class BookController : Controller
{
private IBookService _bookService;
public BookController(IBookService bookService)
{
_bookService = bookService;
}
// GET: Book
public ActionResult Index()
{
var books = _bookService.GetBooks();
return View(books);
}
}
我的项目使用2个不同的数据库,服务层将从这个通用存储库中实现。我希望myservice1与MyDbContext1一起工作,myservice2与MyDbContext 2 一起工作
然后不要在存储库中new
您的DbContext。无论如何,这使得测试变得困难。
注入:
public Repository(DbContext dbContext)
{
_dbContext = dbContext;
}
现在,存储库不关心注入哪个DbContext派生类。这是因为您只调用DbContext.Set<T>()
。
尝试类似以下操作:
public class MyDbContext1 : DbContext
{
public MyDbContext1 ()
:base("ConnectionString")
{ }
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//...
}
}
并将新属性添加到存储库
private IDbSet<T> Entities
{
get
{
if (_dbSet == null)
{
_dbSet = _dbContext1.Set<T>();
}
return _dbSet;
}
}