0

I'd like init a unity container based on some type from an assembly ("OneOfMyAssemblies"). I'd like register all the types (Class) inherit a specific interface ("IInjectionMarker"). I get them, I create a variable with but I can't use them as a type. The problem is on the line :

unityContainer.RegisterType<interfaceName, typeName> (new InjectionConstructor("MyParameter"));

I get the error "Can't use variable as a type". How can I solve this ?

var types = new List<Type>();

types.AddRange(Assembly.Load("OneOfMyAssemblies")
    .GetTypeListImplementingTheInterface(typeof(IInjectionMarker)));

types.ForEach(h =>
{
    Type typeName= Type.GetType(h.Name, true);
    Type interfaceName = Type.GetType($"I{h.Name}", true);

    unityContainer.RegisterType<interfaceName, typeName> (
        new InjectionConstructor("MyParameter"));

});
TheBoubou
  • 19,487
  • 54
  • 148
  • 236
  • 1
    Have you tried `unityContainer.RegisterType(interfaceName, typeName, new InjectionConstructor("MyParameter"));`? – John Wu Oct 10 '20 at 07:26

1 Answers1

0

Unfortunately you cannot use types for generic methods like this.

Option 1: using non-generic method

After briefly checking the docs I found out that RegisterType<TFrom, TTo>(IUnityContainer, InjectionMember[]) is just extension method of IUnityContainer and you can use one method of IUnityContainer, which is RegisterType(Type, Type, String, ITypeLifetimeManager, InjectionMember[]), for more details about all the parameter check the docs at link to some unity docs

Should work like this:

Type toType = Type.GetType(h.Name, true);
Type fromType = Type.GetType($"I{h.Name}", true);

unityContainer.RegisterType(fromType, toType, null, null, new InjectionConstructor("MyParameter"));

Option 2: generating generic method via reflection

If really want to use the generic extension method I refer you to this answer, which will show how to generate and call such method: https://stackoverflow.com/a/232621/5991722

CrudaLilium
  • 654
  • 7
  • 18