小编Bud*_*lum的帖子

如何使用.NET CORE DI 为同一接口注册多个实现

我有一个名为 ICompleteConsumer 的接口,它只有一种方法,并且该接口有多个实现。

前任:

public class SampleClass1: ICompleteConsumer {

 public async Task Complete(Model model) {
  // do the work
 }
}

public class SampleClass2: ICompleteConsumer {

 public async Task Complete(Model model) {
  // do the work
 }
}
Run Code Online (Sandbox Code Playgroud)

我像这样在启动中注册了这些

services.AddScoped<ICompleteConsumer, SampleClass1>(),
services.AddScoped<ICompleteConsumer, SampleClass2>(), 
Run Code Online (Sandbox Code Playgroud)

我注入这些依赖项如下

public class ConsumerHandlerService(string message) {

 private readonly ICompleteConsumer completeConsumer;

 public ConsumerHandlerService(ICompleteConsumer completeConsumer) {
  this.completeConsumer = completeConsumer
 }

 switch (MessageType) {
  case (MessageType .1) //I want SampleClass1 implementation  to here
  var model = JsonConvert.DeserializeObject < Model > …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection asp.net-web-api asp.net-core

3
推荐指数
1
解决办法
3372
查看次数