2013-05-11 71 views
0

嗨,我正在使用Ninject IoC容器。我無法將結構圖代碼轉換爲ninject。Ninject上下文綁定像結構圖

這是Structuremap代碼結合

For<IProductCatalogService>().Use<ProductCatalogService>().Named("realProductCatalogService"); 
For<IProductCatalogService>().Use<CachedProductCatalogService>() 
        .Ctor<IProductCatalogService>().Is(p => p.TheInstanceNamed("realProductCatalogService")); 

而且我使用Ninject這樣的代碼

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

但這不工作。

+0

請參閱http://stackoverflow.com/questions/8447037/how-the-binding-are-done-with-decorators-using-ninject – 2013-05-12 00:24:33

回答

1

我建議你想將IProductCatalogService的一些實現注入到CachedProductCatalogService中,該實現也實現了IProductCatalogService,然後在應用程序的其餘部分中使用此緩存實現作爲默認組件。

隨着Ninject您可以使用它配置了.WhenParentNamed有條件的結合是這樣的:

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

Kernel.Bind<IProductCatalogService>() 
     .To<CachedProductCatalogService>() 
     .Named("cached"); 

當存在IProductCatalogService ninject將盡力解決條件的請求。如果父組件(詢問注射)名稱爲"cached"(您的案例中的CachedProductCatalogService)比ninject將返回ProductCatalogService否則它將返回CachedProductCatalogService作爲默認值。