【发布时间】:2015-10-27 22:30:29
【问题描述】:
我今天遇到一个问题,我无法解决,我搜索了很多,无法找到解决方案,如果可以,请帮助我。
我正在实现一个 MVC 应用程序,它使用 EF + 存储库模式 + 使用 Autofac 作为依赖注入器的工作单元。
我能够使用一个 DbContext 类,但我面临需要使用另一个 DbContext 实例(使用另一个用户凭据访问另一个数据库)的情况
让我更好地解释一下:我有来自数据库 A 的 EntityA(并且有一个 DatabaseA_Context 类)。所以我需要一个EntityB,它来自数据库B(有自己的DatabaseB_Context 类)。
当我向 AutoFac 注册它们时,只有最后配置的依赖项被注入到 GenericRepository 实现中。
我已经找到文章说 Autofac 使用最后一个值覆盖注册。
我已经找到另一篇文章显示如果我在 UnitOfWork 构造函数上传递一个 IEnumerable,我可以看到它的所有注册类型,但我想要一个特定的类型。
我够清楚了吗?
我的代码如下:
我的控制器:
public class MyController : Controller
{
private readonly IBaseBLL<EntityA> _aBLL;
private readonly IBaseBLL<EntityB> _bBll;
public MyController(IBaseBLL<EntityA> aBLL, IBaseBLL<EntityB> bBLL)
{
_aBLL = aBLL;
_bBLL = bBLL;
}
}
我的业务层
public interface IBaseBLL<T> where T : class
{
T Select(Expression<Func<T, bool>> predicate);
T AddT entity);
void Update(T entity);
T Delete(T entity);
}
public class BaseBLL<T> : IBaseBLL<T> where T : class
{
private readonly IUnitOfWork _uow;
public BaseBLL(IUnitOfWork uow)
{
_uow = uow;
}
//implementation goes here...
}
我的 UOW 实现
public interface IUnitOfWork : IDisposable
{
int SaveChanges();
IGenericRepository<T> Repository<T>() where T : class;
}
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _dbContext;
private bool disposed = false;
private Dictionary<Type, object> repositories;
public UnitOfWork(DbContext dbContext)
{
_dbContext = dbContext;
repositories = new Dictionary<Type, object>();
}
public IGenericReposity<T> Repository<T>() where T : class
{
if (repositories.Keys.Contains(typeof(T)))
return repositories[typeof(T)] as IGenericReposity<T>;
IGenericReposity<T> repository = new GenericRepository<T>(_dbContext);
repositories.Add(typeof(T), repository );
return repository ;
}
public int SaveChanges()
{
return _dbContext.SaveChanges();
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
if (disposing)
_dbContext.Dispose();
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
我的存储库实现
public class GenericRepository<T> : IGenericRepositoryT> where T : class
{
protected readonly DbContext _dbContext;
protected IDbSet<T> _dbSet;
public GenericRepository(DbContext dbContext)
{
_dbContext = dbContext;
_dbSet = _dbContext.Set<T>();
}
//implementation goes here...
}
我的 AutoFac 注册(在 Global.asax 文件中)
var builder = new ContainerBuilder();
builder.RegisterType(typeof(DatabaseA_Context)).As(typeof(DbContext)).InstancePerLifetimeScope();
builder.RegisterType(typeof(DatabaseB_Context)).As(typeof(DbContext)).InstancePerLifetimeScope();
builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerRequest();
请帮忙
【问题讨论】:
-
在使用多个数据库和 Autofac 时,我遇到了和你一样的问题。你做了什么来解决这个问题?您是刚刚在 autofac 中创建了 2 个 dbcontext 实例,还是为您的工作单元做了同样的事情?每个对应一个 dbcontext?
-
@Mivaweb 在您的服务类的 DbContext 参数之前使用 [WithKey] 属性
标签: c# entity-framework repository-pattern autofac unit-of-work