How to register multiple implementations of the same interface in Asp.Net Core?

前端 未结 24 1962
不思量自难忘°
不思量自难忘° 2020-11-22 10:16

I have services that are derived from the same interface.

public interface IService { }
public class ServiceA : IService { }
public class ServiceB : IService         


        
24条回答
  •  执念已碎
    2020-11-22 10:41

    Bit late to this party, but here is my solution:...

    Startup.cs or Program.cs if Generic Handler...

    services.AddTransient, CustomerSavedConsumer>();
    services.AddTransient, ManagerSavedConsumer>();
    

    IMyInterface of T Interface Setup

    public interface IMyInterface where T : class, IMyInterface
    {
        Task Consume();
    }
    

    Concrete implementations of IMyInterface of T

    public class CustomerSavedConsumer: IMyInterface
    {
        public async Task Consume();
    }
    
    public class ManagerSavedConsumer: IMyInterface
    {
        public async Task Consume();
    }
    

    Hopefully if there is any issue with doing it this way, someone will kindly point out why this is the wrong way to do this.

提交回复
热议问题