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

标签 c# entity-framework repository-pattern autofac unit-of-work

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

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

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

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

当我使用 AutoFac 注册它们时,只有最后配置的依赖项被注入(inject)到 GenericRepository 实现中。

我已经找到文章说 Autofac 会用最后一个值覆盖注册。

我已经找到了其他文章,其中显示如果我在 UnitOfWork 构造函数上传递 IEnumerable,我能够看到它的所有已注册类型,但我想要一个特定的类型。

我够清楚吗?

我的代码如下:

我的 Controller :

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>()

关于c# - UOW + Repository + Autofac 加载两个不同的 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33379624/

相关文章:

c# - Xamarin Forms - 检查 Environment.SpecialFolder.DesktopDirectory 中是否存在文件

entity-framework - 多个表中的一对一映射

c# - 在通用存储库函数中选择特定列

nhibernate - 存储库/工作单元模式 - 如何在存储库中查询满足特定条件的对象?

c# - ETW 格式字符串中的转义字符?

c# - 从 Azure 上运行的辅助角色服务访问 Sharepoint

c# - 从表示层映射到后端的通用方式

c# - 手动运行 Entity Framework 迁移 Seed() 方法,包括在 Down() 迁移之后

c# - 使用 DDD 和 AutoMapper,您如何在单个工作单元内处理多个服务中的同一个聚合根?

c# - 如何从字节数组中删除空值?