【问题标题】:Contextual Binding in .NET Core 2.2 DI Container?.NET Core 2.2 DI 容器中的上下文绑定?
【发布时间】:2019-03-24 18:01:57
【问题描述】:

在.NET框架中,可以使用Ninject实现上下文绑定。

例如:

Bind<IWarrior>().To<Samurai>().WhenInjectedInto(typeof(OnLandAttack));
Bind<IWarrior>().To<SpecialNinja>().WhenInjectedInto(typeof(AmphibiousAttack));

这意味着您可以根据注入的内容注入不同的具体实现。

我在 .NET Core 2.2 中看不到任何实现相同功能的方法 - 这是不可能的,还是只需要一些额外的配置?

来自Ninject site的示例代码

【问题讨论】:

  • 你说看不到方法是什么意思?您从文档中获取了上面的代码,它不起作用吗?
  • 我觉得这在 .NET Core @DavidG 中不可用
  • MS.DI 中没有这样的功能。
  • 看到这个so answer
  • Microsoft.Extensions.DependencyInjection 在技术上不支持上下文绑定,尽管您可以通过工厂重载以某种有限的方式做到这一点,即您可以提供一个 Lamba“工厂”作为服务注册,并且在其中lambda 确定要返回的实际实例。如果您需要比这更强大的东西,那么您将需要使用备用 DI 容器,例如 Autofac。请参阅:github.com/aspnet/Extensions/tree/master/src/…。应该注意的是,目前不支持 Ninject。

标签: c# asp.net-core dependency-injection .net-core ninject


【解决方案1】:

我需要这样的东西并最终为它创建了一个 NuGet 包:https://www.nuget.org/packages/ServiceProviderContextualBinding/

用法如下:

services.AddSingleton<IService, DefaultService>();
services.AddSingleton<ReplacementService>();
services.WithReplacement<IService, ReplacementService>()
    .AddSingleton<Consumer>();

这个包基本上是 the ActivatorUtilities.CreateInstance method 的一个外观,它是 MS DI 代码的一部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2020-09-20
    • 2019-10-03
    • 2020-08-25
    • 2021-04-14
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多