gpt4 book ai didi

c# - .NET Core 2.2 DI 容器中的上下文绑定(bind)?

转载 作者:行者123 更新时间:2023-12-05 07:24:35 25 4
gpt4 key购买 nike

在.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com