簡體   English   中英

注冊不同類型的同一個班級

[英]Register same class for different types

我有一些實現它們各自特定接口的類,但也有一個共享接口。 我需要能夠根據需要的特定類型來獲取每個對象,還需要獲取共享接口服務的列表。

//Classes
public class ClassA : IServiceA, IHealthReporter

public class ClassB : IServiceB, IHealthReporter

public class ClassC : IServiceC, IHealthReporter

public class Manager : IManager
{
    public Manager(IServiceA serviceA, IServiceC IServiceC)
    {
        //Works as expected
    }
}

public class HealthReporter : IHealthReporter
{
    private readonly IEnumerable<IHealthReporter> _healthReporters;

    public Manager(IEnumerable<IHealthReporter> healthReporters)
    {
        //Getting an empty list here

        _healthReporters = healthReporters;
    }

    public IDictionary<string, string> GetHealthStatus()
    {
        var result = new Dictionary<string, string>();

        foreach(var healthReporter in healthReporters)
        {
            result.Add(healthReporter.GetName(), healthReporter.IsHealtht().ToString());
        }

        return result;
    }
}

//Registration
builder.RegisterType<ClassA>().As<IServiceA>();
builder.RegisterType<ClassB>().As<IServiceB>();
builder.RegisterType<ClassC>().As<IServiceC>();

builder.RegisterType<Manager>().As<IManager>();
builder.RegisterType<HealthReporter>().As<IHealthReporter>();

這些是我正在使用的版本:

<package id="Autofac" version="4.8.1" targetFramework="net452" />
<package id="Autofac.Mvc5" version="4.0.2" targetFramework="net452" />
<package id="Autofac.WebApi2" version="4.1.0" targetFramework="net452" />

我需要獲取IHealthReporter類型的所有實例。

我應該如何注冊這些類以使用這兩種類型進行訪問而又不注冊多個?

您需要讓Autofac知道這些類在注冊期間也實現了IHealthReporter

builder.RegisterType<ClassA>().As<IServiceA>().As<IHealthReporter>();
builder.RegisterType<ClassB>().As<IServiceB>().As<IHealthReporter>();
builder.RegisterType<ClassC>().As<IServiceC>().As<IHealthReporter>();

或更短:

builder.RegisterType<ClassA>().AsImplementedInterfaces();
builder.RegisterType<ClassB>().AsImplementedInterfaces();
builder.RegisterType<ClassC>().AsImplementedInterfaces();

除此之外,使用者( HealthReporter )和依賴項( ClassAClassBClassC )不應實現相同的接口,這很奇怪,這可能是Autofac不將HealthReporter注入HealthReporterHealthReporter因為它會導致無限循環(或導致堆棧溢出)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM