繁体   English   中英

对依赖注入感到困惑

[英]Confused about dependency injection

我有一个工作单元类,其中包含一个ExpressionRepository。 我想将其替换为接口(IExpressionRepository)并使用Ninject将其绑定到ExpressionRepository,但这是问题所在:我的ExpressionRepository希望将DbContext作为构造函数参数,但是据我所知您无法在接口中定义构造函数,因此如果不使用具体的实现,就无法调用此构造函数。

这是现在的代码,没有使用接口:

    private DbContext _dbContext;
    private ExpressionRepository _expressionRepository;

    public UnitOfWork(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public ExpressionRepository ExpressionRepository
    {
        get { return _expressionRepository ?? (_expressionRepository = new ExpressionRepository(_dbContext)); }
    }

我最好的猜测是在接口中添加诸如“ void setDataSource(Object dataSource)”之类的方法,但是还有更好的方法吗?

您的问题尚不完全清楚,但是如果问题是您无法在设置DI容器的那DbContext设置DbContext (因此无法直接注入IExpressionRepository ),那么解决方案这是注入工厂:

public interface IExpressionRepositoryFactory
{
    IExpressionRepository Create(string someIdentifier);
}

在这里, someIdentifier是你需要设置的任何信息DbContext (例如连接字符串或者更好的是,一些实现独立的ID,可以映射到工厂内的连接字符串)。 如果您知道不需要该参数,则可以完全省略该参数(例如,您将要读取配置文件)。

然后,将工厂注入需要存储库的任何类中,并可以适当地指定someIdentifier

通常,您要做的就是将存储库传递(注入)到工作单元中,因此UoW并不直接依赖于DbContext而只是使用“存储库具有的任何机制”,无论它是DbContext还是SqlClient或其他一些ORM。

如果您对始终拥有DbContext感到满意,则可以执行以下操作-但这意味着任何存储库实现都将始终必须回到DbContext

IExpressionRepository Create(DbContext context);

这仍然使IExpressionRepository本身与DbContext类分离,而不仅仅是工厂接口。

如果您不想使用@Ant P提到的工厂方法,请使用方法绑定:

Bind<IExpressionRepository>().ToMethod(context => new ExpressionRepository(GetMyDbContext()));

或者,您可以使用常规绑定,其中ExpressionRepository类将DBContext作为其构造函数中的参数,并绑定DBContext

 Bind<DBContext>().ToSelf().InRequestScope();
 Bind<IExpressionRepository>().To<ExpressionRepository>();

看看这个问题,我猜它有相同的方法:

使用Ninject时如何处理DBContext

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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