简体   繁体   English

autofac从同一接口继承的多个类

[英]autofac multiple classes inherited from the same interface

Im using autofac to inject my dependencies into my classes. 我使用autofac将依赖项注入类中。 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 pdfHedgeReport

but its actually using this one pdfRefVolReport 但它实际上使用的是这个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 它实际上不是被访问的pdfHedgereport类,它的pdfRefVolReport

so am I registering these the wrong way with autofac ?? 所以我用autofac错误地注册了这些方式吗?

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 . 您可能想查看如何通过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. 这就是我在使用Autofac时正在做这类事情的方式,并且效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM