繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM