[英]UOW + Repository + Autofac load two different DbContext
我今天面臨一個問題而且我無法解決它,我搜索了很多但無法解決問題,請盡可能幫助我。
我正在實現一個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();
請幫忙
您應該使用命名和密鑰服務
builder.RegisterType<DatabaseA_Context>()
.Named<DbContext>("databaseA")
.InstancePerLifetimeScope();
builder.RegisterType<DatabaseB_Context>()
.Named<DbContext>("databaseB")
.InstancePerLifetimeScope();
然后,您可以在注冊時為組件指定所需的DbContext
builder.RegisterType<MyService>()
.As<IService>()
.WithParameter((pi, c) => pi.Name == "dbContext",
(pi, c) => c.ResolveNamed<DbContext>("databaseA"))
或者使用IIndex<,>
public class MyService : IService
{
public MyService(IIndex<String, DbContext> 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<DbContext>("databaseA"))
.As<DbContext>()
.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<DbContext>("databaseA");
}
else if (pi.Name.Equals("dbContextB", StringComparison.OrdinalIgnoreCase))
{
return c.ResolveNamed<DbContext>("databaseB");
}
else
{
throw new NotSupportedException($"DbContext not found for '{pi.Name}' parameter name");
}
});
e.Parameters = e.Parameters.Concat(new Parameter[] { parameter });
}
}
和
builder.RegisterModule<DbContextModule>()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.