C# Ninject上下文绑定类结构映射

C# Ninject上下文绑定类结构映射,c#,dependency-injection,ninject,ioc-container,ninject-2,C#,Dependency Injection,Ninject,Ioc Container,Ninject 2,嗨,我正在使用Ninject IoC容器。我无法将structuremap代码转换为ninject 这是Structuremap代码绑定 For<IProductCatalogService>().Use<ProductCatalogService>().Named("realProductCatalogService"); For<IProductCatalogService>().Use<CachedProductCatalogService>

嗨,我正在使用Ninject IoC容器。我无法将structuremap代码转换为ninject

这是Structuremap代码绑定

For<IProductCatalogService>().Use<ProductCatalogService>().Named("realProductCatalogService");
For<IProductCatalogService>().Use<CachedProductCatalogService>()
                  .Ctor<IProductCatalogService>().Is(p => p.TheInstanceNamed("realProductCatalogService"));
For().Use().Named(“realProductCatalogService”);
For().Use()
.Ctor().Is(p=>p.TheInstanceNamed(“realProductCatalogService”);
我使用的是这样的Ninject代码

Kernel.Bind<IProductCatalogService>().To<ProductCatalogService>().Named("realProductCatalogService");
Kernel.Bind<IProductCatalogService>().To<CachedProductCatalogService>().Named("cachedProductCatalogService");
Kernel.Bind().To().Named(“realProductCatalogService”);
Kernel.Bind().To().Named(“cachedProductCatalogService”);

但是这不起作用。

我建议您将
IPProductCatalogService
的一些实现注入到
CachedProductCatalogService
中,该实现也实现了
IPProductCatalogService
,然后在应用程序的其余部分使用该缓存实现作为默认组件

使用Ninject,您可以使用
.WhenParentNamed
条件绑定对其进行如下配置:

Kernel.Bind<IProductCatalogService>()
      .To<ProductCatalogService>()
      .WhenParentNamed("cached");

Kernel.Bind<IProductCatalogService>()
      .To<CachedProductCatalogService>()
      .Named("cached");
Kernel.Bind()
.至()
.WhenParentNamed(“缓存”);
Kernel.Bind()
.至()
.命名为(“缓存”);
当有
IPProductCatalogService
ninject请求时,ninject将尝试解决这些问题。如果父组件(请求注入的组件)被命名为
“cached”
(在本例中为
CachedProductCatalogService
),ninject将返回
ProductCatalogService
,否则它将返回
CachedProductCatalogService
,作为默认值。

请参阅