Reputation: 15860
I have the following interface
public interface ICheckEvaluator<in TCheck> where TCheck : ResourceCheck
that needs to be injected with the following implementation:
public class OutageCheckEvaluator : ICheckEvaluator<OutageCheck>
Can someone provide an advice as to how this can be done? OutageCheck inherits from ResourceCheck:
public partial class OutageCheck : ResourceCheck
The following method didnt work:
builder.RegisterType<OutageCheckEvaluator>().As<ICheckEvaluator<OutageCheck>>();
as Autofac receives ICheckEvaluator(ResourceCheck) to implement and cannot match it to ICheckEvalutor(OutageCheck)
Appreciate any advice here.
Upvotes: 1
Views: 984
Reputation: 1124
You could resolve those Evaluators
by using e.g. reflection.
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{}
but the problem is that since generic parameter is contravariant you cannot do any of those casts
var test = new OutageCheck() as ICheckEvaluator<ResourceCheck>;
var evaluator = container.Resolve(interfaceType) as ICheckEvaluator<ResourceCheck>;
Is there any special need you have ICheckEvaluator<in TCheck>
instead of ICheckEvaluator<out TCheck>
?
Upvotes: 1