简体   繁体   中英

Reflection of generic method not working

I have a generic static method which registers a interface and I need to write that using c# reflection.

Services.AddService<ITBroker>(new TBrokerService());

I tried following code but it is not working

Type[] externTBrokerService = Assembly.LoadFrom("Business.dll").GetTypes();
Type[] externService = Assembly.LoadFrom("ServiceModel.dll").GetTypes();
Type iTBroker = externITBroker[12];
MethodInfo method = externService[1].GetMethods()[2];
//Gets Add Service method
MethodInfo generic = method.MakeGenericMethod(iTBroker);
//Make method generic           
generic.Invoke(null,new object[] { externTBrokerService[0]});
//invoke the service

Above code gives me very generic exception of parameters.

What is the write way to write reflection for above code?

As it was in comments:

Note that externTBrokerService[0] is a Type and not an instance of that type.

Having that I feel a need to include sense of other comments as part of my answer.

Type iTBroker = externITBroker[12];

this is wrong! And sooner or later this will fail to find your type as the order of types in this collection is undetermined and can change. You should do it like this:

Type iTBroker = externITBroker.Single(x => x.Name == "ITBroker");

This is far form foolproof so be sure that the condition gives you unique result.

or simply load that type directly by (assuming that this is the AssemblyQualifiedName of your type):

Type.GetType("Business.ITBroker, Business");

To find method on your type there is a method Type.GetMethod one of its overloads will be sufficient to find your method.

To create instance of your type that needs to be passed as argument you can use

Activator.CreateInstance(brokerServiceType);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM