UOW + Repository + Autofac 加载两个不同的 DbContext

UOW + Repository + Autofac load two different DbContext

我今天遇到一个问题,我无法解决,我搜索了很多都没有找到解决方案,如果可以的话请帮助我。

我正在实现一个 MVC 应用程序,它使用 EF + 存储库模式 + 工作单元和 Autofac 作为依赖注入器。

我能够使用一个 DbContext class,但我面临的情况是我需要使用另一个 DbContext 实例(它使用另一个用户凭据访问另一个数据库)

让我更好地解释一下:我有来自数据库 A 的 EntityA(并且有一个 DatabaseA_Context class)。所以我需要一个 EntityB,它来自数据库 B(有它自己的 DatabaseB_Context class)。

当我用 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(); 

请帮忙

你应该使用 Named and Keyed Service

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)
    {
    }
}

See the metadata documentation 了解有关如何设置 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>()