C# 使用Ninject时深度大于1的上下文/条件依赖项注入?

C# 使用Ninject时深度大于1的上下文/条件依赖项注入?,c#,asp.net-mvc,dependency-injection,ninject,ninject-2,C#,Asp.net Mvc,Dependency Injection,Ninject,Ninject 2,我有一个IDataContext接口,该接口由一个InMemoryDataContext和MyApplicationDataContext实现。这是我的所有存储库使用的,这些存储库定义为BananaRepository:ibanarepository,并在其构造函数中获取数据上下文: interface IDataContext {} class InMemoryDataContext : IDataContext {} class MyApplicationDataContext : IDat

我有一个
IDataContext
接口,该接口由一个
InMemoryDataContext
MyApplicationDataContext
实现。这是我的所有存储库使用的,这些存储库定义为
BananaRepository:ibanarepository
,并在其构造函数中获取数据上下文:

interface IDataContext {}
class InMemoryDataContext : IDataContext {}
class MyApplicationDataContext : IDataContext {}

interface IBananaRepository {}
class BananaRepository : IBananaRepository 
{
    public BananaRepository(IDataContext dataContext) {}
}
到目前为止,我的接口和服务消费者是ASP.NET MVC控制器、同步命令和查询。NInject在我的Web项目中配置,
IDataContext
通过
InRequestScope()
绑定到
MyApplicationDataContext

我希望当NInject实例化
IAsyncCommand
的类实现时,
ibanarepository
(以及我的所有其他存储库)用
IDataContext
的新实例初始化,而不是用于重用web请求的实例(实际上,我希望将
IAsyncCommand
my
IDataContext
绑定为
InTransientScope()

我该怎么做

另外:我使用CommonServiceLocator而不是Ninject内核直接实例化IAsyncCommand实例。

请看


在这里,您可以找到IsAnyAnchestorNamed。您可以使用相同的循环,并将其与WhenInjectedTo中找到的条件相结合,然后从中调用它。

不仅仅是一个简单的“kernel.Bind().To().WhenInjectedTo().InTransientScope();”binding do?@Hari No,因为上下文被注入到存储库中,而不是命令中。谢谢-我今天晚些时候将研究如何实现它,并将返回给您(以及这个问题/答案)。嗯。因此,如果我完成了这项工作,并拥有
pbulic DoSomethingAsyncCommand(IREP1 rep1,IREP2 rep2)
我使用
TransientScope
它将有效地创建两个
IDataContext
实例?我该如何解决这个问题?是我自己还是我所想的不可能,因为在实例化数据上下文时,没有对存储库的引用,也没有对用作范围对象的命令的引用?我想在我的场景中使用工厂可能更好?您可以使用命名的范围扩展将命令用作范围。
 kernel.Bind<IDataContext>().To<MyApplicationDataContext>().InRequestScope();
 kernel.Bind<IBananaRepository>().To<BananaRepository>();
class DoSomethingAsyncCommand : IAsyncCommand<TArgs>
{
    public DoSomethingAsyncCommand(IBananaRepository repository) {}

    public bool Execute(TArgs args) {}
}