Search code examples
c#.net.net-corereflection

Operator '<' cannot be applied to operands of type 'method group' and 'Type'


I'm trying to register automatically the classes for Dependency Injection in a loop instead of manually. However the method I'm using is not compiling.

Method that is working:

containerBuilder.RegisterType<MyClass>().As<IMyClass>();

Method that doesn't compile:

List<Type> servicesList = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace.Services").Where(type => type.IsClass && !type.IsAbstract && !type.IsGenericType && !type.IsNested).ToList<Type>();
for (int i = 0; i < servicesList.Count; i++)
{
    containerBuilder.RegisterType<servicesList[i]>();
}

The compiler throws this error message:

Operator '<' cannot be applied to operands of type 'method group' and 'Type'


Solution

  • You are using generic arguments incorrectly.

    You can register by type

    containerBuilder.RegisterType(servicesList[i]);
    

    Reference Reflection Components: Register by Type