我有以下界面
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)匹配
在此欣赏任何建议。
答案 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>
?