c# - 当有多个实现接口的类时,如何指定构造函数注入
问题描述
我想对在其构造函数中采用接口 IService 的类使用依赖注入。但是我有这个接口的几个实现。其他类也需要这两种实现,所以我不能简单地只启动需要的那个。我正在使用 Microsoft.Extensions.DependencyInjection
这是一个尝试显示我的课程的示例
public interface IService { }
public class ServiceA : IService { ... }
public class ServiceB : IService { ... }
public class Foo
{
public Foo(IService service) { }
}
public class Bar
{
public Bar(IService service) { }
}
如果我没有几个实现,我会像下面这样注入它:
builder.Services.AddSingleton<IService, ServiceA>();
builder.Services.AddSingleton<Foo>();
在示例中,我需要使用 ServiceA 初始化 Foo,使用 ServiceB 初始化 Bar。
解决方案
像这样(直接在浏览器中输入):
builder.Services.AddSingleton<ServiceA>();
builder.Services.AddSingleton<ServiceB>();
builder.Services.AddSingleton<Foo>(c =>
ActivatorUtilities.CreateInstance<Foo>(c, c.GetRequiredService<ServiceA>()));
builder.Services.AddSingleton<Bar>(c =>
ActivatorUtilities.CreateInstance<Bar>(c, c.GetRequiredService<ServiceB>()));
推荐阅读
- reactjs - RangeError: Invalid typed array length: -4095 when running my react web app
- c++ - 如果我在各自的 char 数组的声明中为其提供额外的元素,是否会自动设置 NUL?
- django - 将 Python 应用部署到 Windows Server 上的 Azure 应用服务
- node.js - (discord.js) 为作者添加角色
- ruby-on-rails - 有没有办法在 Rails 中编写 HTML 表单?
- cassandra - 使用 Cassandra 进行排序
- python - 我不明白为什么我的 super() 会产生错误
- elasticsearch - 尝试构建同义词过滤器时收到“无法构建同义词”消息
- git - 如何忽略特定文件之外的所有文件(不要忽略)
- java - 如何获取包含的 FXML 的控制器?