Ninject参数名称基础依赖注入

Parameter name base dependency injection with Ninject

我试过寻找答案,可能只是搜索不好。我找到的结果没有帮助,所以如果你找到我正在寻找的答案,请指出力的方向。

我正在尝试根据名称注入构造函数参数。

public class ReportController : Controller
{
    public ReportController(IUOW replication)
    {
    }
}
public class NormalController : Controller
{
    public NormalController(IUOW uow)
    {
    }
}

所以在 ninjectwebcommon 文件中,我试图根据参数名称向我的控制器注入初始化参数。这是有效的绑定,但随后都指向同一个实例。

kernel.Bind<IUOW>().ToConstructor(i => new UOW(new DatabaseContext()));

我已经尝试了很多答案,但总是失败。对我搜索失败的任何帮助或 url 指导将不胜感激。我想将工作单元绑定到复制数据库上下文,否则绑定到普通上下文。我想说内核应该将名为 replication 的构造函数中的所有 IUOW 绑定到 new UOW(new ReplicationContext()) 否则 new UOW(new DatabaseContext())

您尝试过使用命名绑定吗?在此处查看文档:

https://github.com/ninject/Ninject/wiki/Contextual-Binding

public class ReportController : Controller
{
    public ReportController([Named("replication")]IUOW replication)
    {
    }
}
public class NormalController : Controller
{
    public NormalController([Named("uow")]IUOW uow)
    {
    }
}

然后您将以这种方式绑定它们

kernel.Bind<IUOW>().ToConstructor(i => new UOW(new DatabaseContext())).Named("uow");
kernel.Bind<IUOW>().ToConstructor(i => new SomethingElse(new DatabaseContext())).Named("replication");