【问题标题】:UOW + Repository + Autofac load two different DbContextUOW + Repository + Autofac 加载两个不同的 DbContext
【发布时间】: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


【解决方案1】:

你应该使用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&lt;,&gt;

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

【讨论】:

  • 最后一种方法解决了我的问题,谢谢你的帮助!
猜你喜欢
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-27
  • 2018-10-12
相关资源
最近更新 更多