Search code examples
.netdependency-injectionunity-container

How proper define ParameterOverride for abstract type in constructor for IUnityContainer


I have some classes:

public class Inspector
{
        private readonly BaseType someType;

        public Inspector(BaseType someType)
        {
            this.someType= someType;
        }
}

public abstract class BaseType {}

public class TypeA : BaseType {}

public class TypeB : BaseType {}

and IoC container setup for them:

var container = new UnityContainer();
container.RegisterType<Inspector>();

then during runtime I have call to something like this:

var typeA = new TypeA(); //It could be also TypeB
var inspector = container.Resolve<Inspector>(new ParameterOverride(typeA.GetType(), typeA));

but this Resolve<Inspector>() gives me an exception: The current type, BaseType, is an abstract class and cannot be constructed. Are you missing a type mapping? It looks like parameter override is ignored and container tries find BaseType registration in it. Of course registration of TypeA and TypeB doesn't solve the problem. Anyway I don't want register all subtypes of BaseType in the container because there is a lot of classes.


Solution

  • UnityContainer tries to resolve BaseType, not a type inhertied from BaseType.

    So you need to create the override for BaseType:

    var inspector = container.Resolve<Inspector>(new ParameterOverride(typeof(BaseType), typeA));