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

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

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

相关文章:

c# - 在 C# 中隐藏大括号

c# - 检查一个 IList 改变了吗?

c# - 500, 无效操作异常 : No route matches the supplied values

c# - 在中间件.net core 2.0中获取访问 token

dependency-injection - 如何配置一个新的 IDataBus 实现,该实现具有需要注入(inject)到 NServiceBus 中的依赖项?

asp.net-mvc - 将依赖项注入(inject)自定义模型绑定(bind)器并使用 InRequestScope 使用 Ninject

c# - 如果一个方法在 linq 查询中,它会被多次调用吗?

c# - DependencyResolutionException 检测到循环组件依赖性 : How to use Autofac to inject decorator?

selenium-webdriver - 使用 Headless 浏览器测试 ASP.Net 5 UI(适用于 Windows、Mac 和 Linux)

dependency-injection - 使用 Unity IoC 注册和解析 SignalR 集线器