【发布时间】:2018-10-22 11:52:47
【问题描述】:
我有一个通用的 UnitOfWork 模式实现,这些 UnitOfWork 对象是我的服务类的依赖项。下面的 sn-ps 应该可以帮助读者理解我的代码设置:
IUnitOfWork 接口
public interface IUnitOfWork<out TContext> where TContext : IDbContext
UnitOfWork 类
public sealed class UnitOfWork<TContext> : IDisposable, IUnitOfWork<IDbContext> where TContext : IDbContext
{
private static readonly ILog Log = LogManager.GetLogger(typeof(UnitOfWork<TContext>));
private readonly IDbContext _dbContext;
private Dictionary<string, IRepository> _repositories;
private IDbTransaction Transaction { get; set; }
public UnitOfWork(IDbContext context)
{
_dbContext = context;
}
}
容器注册:
builder.RegisterGeneric(typeof(UnitOfWork<>)).As(typeof(IUnitOfWork<>));
builder.RegisterType<ReconciliationDbContext>().As<IDbContext>();
builder.RegisterType<GenevaDataDbContext>().As<IDbContext>();
builder.RegisterType<OpenStaarsDbContext>().As<IDbContext>();
builder.RegisterType<UnitOfWork<ReconciliationDbContext>>().Keyed<IUnitOfWork<IDbContext>>(ContextKey.Recon);
builder.RegisterType<UnitOfWork<OpenStaarsDbContext>>().Keyed<IUnitOfWork<IDbContext>>(ContextKey.OpenStaars);
builder.RegisterType<CommentsService>().As<ICommentsService>().WithAttributeFiltering();
DbContext 类:
public class ReconciliationDbContext : BaseDbContext<ReconciliationDbContext>, IDbContext
{
private const string DbSchema = "BoxedPosition";
public ReconciliationDbContext() : base("Reconciliation")
{
}
}
public class OpenStaarsDbContext : BaseDbContext<OpenStaarsDbContext>, IDbContext
{
public OpenStaarsDbContext() : base("OpenStaars")
{
}
}
CommentsService 类:
public class CommentsService : ICommentsService
{
private readonly IUnitOfWork<IDbContext> _reconciliationUoW;
public CommentsService([KeyFilter(ContextKey.Recon)] IUnitOfWork<IDbContext> reconciliationUoW)
{
_reconciliationUoW = reconciliationUoW;
}
}
解决 ICommentsService:
var commentsService = container.Resolve<ICommentsService>();
现在,当我尝试解析 ICommentsService 类型时,它会实例化 UnitOfWork 依赖项。但是,UnitOfWork._dbContext 属性的计算结果为 OpenStarsDbContext 类型。考虑到我们的注册情况,这尤其奇怪。
如果我们通过在 OpenStarsDbContext 之后注册 GenevaDataDbContext 来重新排序我们的 IDbContext 注册,那就更奇怪了。现在 _dbContext 评估为 GenevaDataDbContext 实例。
如何解决此问题,以使 CommentsService 的和解UoW 依赖项具有正确的 ReconciliationDbContext 实例?
【问题讨论】:
标签: c# dependency-injection inversion-of-control autofac