1

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.

Igorek
  • 15,716
  • 3
  • 54
  • 92

1 Answers1

1

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>?

Vladimir Sachek
  • 1,126
  • 1
  • 7
  • 20
  • I was/am getting an error that OutageCheckEvaluator cannot be cast to ICheckEvaluator. – Igorek May 14 '14 at 06:53
  • Could you provide more code samples to reproduce that? – Vladimir Sachek May 14 '14 at 06:56
  • Sorry for late reply, my issue is that I dont resolve objects like you did in the test. I have a List that I run through, and for every one of them, I instantiate a factory that tries to create an Evaluator object. I dont know the type of each ResourceCheck until the code runs. – Igorek May 14 '14 at 12:12
  • I did have to use contravariance, but found this post to help with casting: http://stackoverflow.com/questions/7010236/customizing-autofacs-component-resolution-issue-with-generic-co-contravarian – Igorek May 14 '14 at 13:33