C# Ninject上下文绑定类结构映射
嗨,我正在使用Ninject IoC容器。我无法将structuremap代码转换为ninject 这是Structuremap代码绑定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>
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
,作为默认值。请参阅