I have an issue with co/contra-variance. I understand you can’t have both input and output. So here is a simple example:
public interface A<T>
{
T Object {get;set;}
}
public interface B
{
// Some stuff
}
public class BImplementor : B
{ }
public class Implementor : A<BImplementor> {}
Suppose you have these classes and I’m wanting to write a method like this
public void Command(B obj)
{
var a = (A<B>)Unity.Resolve(typeof(A<>).MakeGenericType(obj.GetType());
a.Object = obj;
}
I’m using Unity to resolve a A of the specifc implementor of B (specifically Implementor), but all I know about it is that it is an A<B>. I don’t know of a way to do this directly and I don’t think it is actually possible, but does anyone know of a workaround to simulate what I’m trying to do.
As you said, you cannot have both input and output, so let’s change
A<T>toA<in T>soCommandcan assignobjto theObjectproperty:The
Commandmethod essentially does this:But this cast can never succeed, because
A<B>.SetObjectmust accept anyBas input, whileImplementor.SetObjectaccepts onlyBImplementorobjects as input!Since you now that you’ll only ever pass a
BImplementortoA<B>.SetObject, you can work around the problem using reflection.Workaround 1:
Workaround 2: