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

前端 未结 24 1964
不思量自难忘°
不思量自难忘° 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:45

    Why not use inheritance? This way we can have as many copies of the interface as we want and we can pick suitable names for each of them . And we have a benefit of type safety

    public interface IReportGenerator
    public interface IExcelReportGenerator : IReportGenerator
    public interface IPdfReportGenerator : IReportGenerator
    

    Concrete classes:

    public class ExcelReportGenerator : IExcelReportGenerator
    public class PdfReportGenerator : IPdfReportGenerator
    

    Register:

    instead of

    services.AddScoped();
    services.AddScoped();
    

    we have :

    services.AddScoped();
    services.AddScoped();
    

    Client:

    public class ReportManager : IReportManager
    {
        private readonly IExcelReportGenerator excelReportGenerator;
        private readonly IPdfReportGenerator pdfReportGenerator;
    
        public ReportManager(IExcelReportGenerator excelReportGenerator, 
                             IPdfReportGenerator pdfReportGenerator)
        {
            this.excelReportGenerator = excelReportGenerator;
            this.pdfReportGenerator = pdfReportGenerator;
        }
    

    this approach also allows for louse coupled code, because we can move IReportGenerator to the core of the application and have child interfaces that will be declared at higher levels.

提交回复
热议问题