Autofac - 基于通用接口和具体类型的注入

时间:2014-05-13 22:49:11

标签: .net generics inversion-of-control autofac

我有以下界面

public interface ICheckEvaluator<in TCheck> where TCheck : ResourceCheck

需要注入以下实现:

public class OutageCheckEvaluator : ICheckEvaluator<OutageCheck>

有人可以就如何做到这一点提出建议吗? OutageCheck继承自ResourceCheck:

public partial class OutageCheck : ResourceCheck

以下方法无效:

builder.RegisterType<OutageCheckEvaluator>().As<ICheckEvaluator<OutageCheck>>();

因为Autofac收到ICheckEvaluator(ResourceCheck)来实现并且无法将其与ICheckEvalutor(OutageCheck)匹配

在此欣赏任何建议。

1 个答案:

答案 0 :(得分:1)

您可以使用例如Evaluators来解决这些问题。反射。

public class AutofacTest
{
    [Test]
    public void Test()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<OutageCheckEvaluator>().As<ICheckEvaluator<OutageCheck>>();
        var container = builder.Build();

        var listOfChecks = new List<ResourceCheck> { new OutageCheck() };
        foreach (var check in listOfChecks)
        {
            var interfaceType = typeof(ICheckEvaluator<>).MakeGenericType(check.GetType());
            var evaluator = container.Resolve(interfaceType);
            Debug.WriteLine(evaluator);
        }
    }
}

public interface ICheckEvaluator<in TCheck> where TCheck : ResourceCheck { }

public class OutageCheckEvaluator : ICheckEvaluator<OutageCheck> { }

public class OutageCheck : ResourceCheck { }

public class ResourceCheck{}

但问题是因为泛型参数是逆变的,所以你不能做任何这些演员

var test = new OutageCheck() as ICheckEvaluator<ResourceCheck>;
var evaluator = container.Resolve(interfaceType) as ICheckEvaluator<ResourceCheck>;

您是否有特殊需要ICheckEvaluator<in TCheck>代替ICheckEvaluator<out TCheck>