UOW + Repository + Autofac加载两个不同的DbContext
我今天面临一个问题,我无法解决,我搜索了很多,无法解决问题,请尽可能帮助我。
我正在实现一个MVC应用程序,该应用程序使用EF +存储库模式+工作单元和Autofac作为dependency injection器。
我能够使用一个DbContext类,但我面临的情况是我需要使用另一个DbContext实例(使用其他用户凭据访问另一个数据库)
让我更好地解释一下:我有来自数据库A的EntityA(并且有一个DatabaseA_Context类)。 所以我需要一个EntityB,它来自数据库B(带有自己的DatabaseB_Context类)。
当我使用AutoFac注册它们时,只会在GenericRepository实现上注入最后配置的依赖项。
我已经发现文章说Autofac用最后一个值覆盖了注册。
我已经发现其他文章显示我是否在UnitOfWork构造函数上传递了IEnumerable,我能够看到它的所有注册类型,但我想要一个特定的类型。
我清楚了吗?
我的代码如下:
我的控制器:
public class MyController : Controller { private readonly IBaseBLL _aBLL; private readonly IBaseBLL _bBll; public MyController(IBaseBLL aBLL, IBaseBLL bBLL) { _aBLL = aBLL; _bBLL = bBLL; } }
我的业务层
public interface IBaseBLL where T : class { T Select(Expression<Func> predicate); T AddT entity); void Update(T entity); T Delete(T entity); } public class BaseBLL : IBaseBLL where T : class { private readonly IUnitOfWork _uow; public BaseBLL(IUnitOfWork uow) { _uow = uow; } //implementation goes here... }
我的UOW实施
public interface IUnitOfWork : IDisposable { int SaveChanges(); IGenericRepository Repository() where T : class; } public class UnitOfWork : IUnitOfWork { private readonly DbContext _dbContext; private bool disposed = false; private Dictionary repositories; public UnitOfWork(DbContext dbContext) { _dbContext = dbContext; repositories = new Dictionary(); } public IGenericReposity Repository() where T : class { if (repositories.Keys.Contains(typeof(T))) return repositories[typeof(T)] as IGenericReposity; IGenericReposity repository = new GenericRepository(_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 : IGenericRepositoryT> where T : class { protected readonly DbContext _dbContext; protected IDbSet _dbSet; public GenericRepository(DbContext dbContext) { _dbContext = dbContext; _dbSet = _dbContext.Set(); } //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();
请帮忙
您应该使用命名和密钥服务
builder.RegisterType() .Named("databaseA") .InstancePerLifetimeScope(); builder.RegisterType() .Named("databaseB") .InstancePerLifetimeScope();
然后,您可以在注册时为组件指定所需的DbContext
builder.RegisterType() .As() .WithParameter((pi, c) => pi.Name == "dbContext", (pi, c) => c.ResolveNamed("databaseA"))
或者使用IIndex<,>
public class MyService : IService { public MyService(IIndex dbContexts) { var databaseA = dbContexts["databaseA"]; } }
Autofac还支持使用WithKeyAttribute
指定命名注册
public class MyService : IService { public MyService([WithKey("DatabaseA")DbContext dbContext) { } }
有关如何设置WithKeyAttribute
详细信息, 请参阅元数据文档 。
使用此解决方案, DbContext
将不会注册。 如果你想要一个默认的DbContext
你可以注册一个这样的:
builder.Register(c => c.ResolveNamed("databaseA")) .As () .InstancePerLifetimeScope();
您还可以使用一个模块,该模块将根据参数的名称选择正确的注册:
public class MyService : IService { public MyService(DbContext dbContextA, DbContext dbContextB) { } }
为此,您需要注册此Autofac模块
public class DbContextModule : Module { protected override void AttachToComponentRegistration( IComponentRegistry componentRegistry, IComponentRegistration registration) { registration.Preparing += Registration_Preparing; } private void Registration_Preparing(Object sender, PreparingEventArgs e) { Parameter parameter = new ResolvedParameter( (pi, c) => pi.ParameterType == typeof(DbContext), (pi, c) => { if (pi.Name.Equals("dbContextA", StringComparison.OrdinalIgnoreCase)) { return c.ResolveNamed("databaseA"); } else if (pi.Name.Equals("dbContextB", StringComparison.OrdinalIgnoreCase)) { return c.ResolveNamed ("databaseB"); } else { throw new NotSupportedException($"DbContext not found for '{pi.Name}' parameter name"); } }); e.Parameters = e.Parameters.Concat(new Parameter[] { parameter }); } }
和
builder.RegisterModule()