为不同类型注册相同的课程

时间:2018-08-06 18:59:12

标签: c# .net autofac

我有一些类,它们分别实现其特定的接口和共享的接口。我需要能够根据需要的特定类型来获取它们,而且还需要获取共享接口服务的列表。

//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类型的所有实例。

我应该如何注册这些类以使用这两种类型进行访问而又不需注册多个?

1 个答案:

答案 0 :(得分:1)

您需要让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注入HealthReporter的原因,因为解决它会导致无限循环(或导致堆栈溢出)。