我有一个项目,我的项目连接到两个不同的数据库是BookStoreEntities和BlogEntities。
如果我在Autofac配置中删除行代码builder.RegisterType<BlogEntities>().As<DbContext>();
,我的项目工作正常,否则我会收到错误&#34; 实体类型Book不是当前上下文模型的一部分&#34;
我的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);
}
}
答案 0 :(得分:2)
我的项目正在使用2个不同的数据库,服务层将从此通用存储库实现。我想myservice1适用于MyDbContext1,myservice2适用于MyDbContext2
然后在您的存储库中不要new
您的DbContext。无论如何,这使得测试很难。
注射它:
public Repository(DbContext dbContext)
{
_dbContext = dbContext;
}
现在,存储库不关心注入哪个DbContext派生类。这是有效的,因为您只需拨打DbContext.Set<T>()
。
答案 1 :(得分:0)
尝试类似:
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;
}
}