Search code examples
c#typesunity-containerioc-container

Register a type at runtime using Unity Container


Why can I not do this? Where obj value is a valid type.

Type type = obj.Value.GetType();
this.unityContainer.RegisterType<type>();

OR

this.unityContainer.RegisterType(obj.Value);

When I can do this... where obj value would be the same type but known at compile time.

this.unityContainer.RegisterType<object, actualType>("Name");

The end goal of mine is to be able to register several different types at run time.


Solution

  • Anything in angle brackets must be known at compile time - generics are a compile-time feature. There are plenty of overloads of RegisterType that take a runtime-determined Type object such as you are doing here.

    Move your runtime type reference out of the angle brackets and into the parentheses.

    this.unityContainer.RegisterType(obj.Value.GetType());