【问题标题】:Ninject contextual bindinng like structuremapNinject 上下文绑定,如结构图
【发布时间】:2013-05-11 19:31:56
【问题描述】:

您好,我正在使用 Ninject IoC 容器。我无法将结构映射代码转换为 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");

但这不起作用。

【问题讨论】:

标签: c# dependency-injection ninject ioc-container ninject-2


【解决方案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作为默认值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    相关资源
    最近更新 更多