在.NET框架中,可以使用Ninject实现上下文绑定(bind)。
例如:
Bind<IWarrior>().To<Samurai>().WhenInjectedInto(typeof(OnLandAttack));
Bind<IWarrior>().To<SpecialNinja>().WhenInjectedInto(typeof(AmphibiousAttack));
这意味着您可以根据要注入(inject)的内容注入(inject)不同的具体实现。
我看不到任何方法可以在 .NET Core 2.2 中实现同样的事情——这是不可能的,还是只需要一堆额外的配置?
示例代码来自 Ninject site
最佳答案
我需要这样的东西并最终为它创建了一个 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 代码的一部分。
关于c# - .NET Core 2.2 DI 容器中的上下文绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326836/