Search code examples
c#interfaceautofacregistration

autofac multiple classes inherited from the same interface


Im using autofac to inject my dependencies into my classes. Several of these classes all implement the same interface. I register them like this

builder.RegisterType<PDFHedgeReport<object>>().As<IPDFReport<object>>().InstancePerDependency();
        builder.RegisterType<PDFRefVolReport<object>>().As<IPDFReport<object>>().InstancePerDependency();

then in my class constructor I have this

public ReportGenerationService(IScheduleRepository scheduleRepository, 
        ExportEngine.PDF.IPDFReport<object> pdfHedgeReport,
        ExportEngine.PDF.IPDFReport<object> pdfRefVolReport,
        )
    {
        this._scheduleRepository = scheduleRepository;
        this._pdfHedgeReport = pdfHedgeReport;
        this._pdfRefVolReport = pdfRefVolReport;

    }

when the code is run, the wrong class is being accessed, the particular branch of code im testing should be using this class

pdfHedgeReport

but its actually using this one pdfRefVolReport

this is the line of code causing the problem

var result = await this._pdfHedgeReport.GenerateReportForEmail(hedgeRequest, reportTitle, reportDescription, rpt);

its not actually pdfHedgereport class thats being accessed, its pdfRefVolReport

so am I registering these the wrong way with autofac ??


Solution

  • By default the type which is registered last will be returned, which is what you are seeing.

    You might want to check out how to register the different types by key.

    The code would look something like this.

    Registration:

    var builder = new ContainerBuilder();
    builder.RegisterType<PDFHedgeReport<object>>().Keyed<ExportEngine.PDF.IPDFReport<object>>("first");
    builder.RegisterType<PDFRefVolReport<object>>().Keyed<ExportEngine.PDF.IPDFReport<object>>("second");
    var container = builder.Build();
    

    Some constructor:

    ctor(IIndex<string, ExportEngine.PDF.IPDFReport<object>> pdfHedgeReportCollection)
    {
        this.hedgeRefReport = pdfHedgeReportCollection["first"];
        this.refVolReport = pdfHedgeReportCollection["second"]
    }
    

    This is how I'm doing this kind of stuff when using Autofac and it works quite well.