mercredi 11 juillet 2018

Create a delegate with an injected instance

I'm changing a process algorithm I've made from reflection to delegate since it handles huge data and it is having performance issues(as I have learned here). So my old code is a simple reflection as shown below:

var result = method.Invoke(service, new object[] { viewModel });

Where method is a MethodInfo, service is a service class with a common method called Add. All services has that method(not generic tho) and this proccess algorithm can run over any service, hence, service(the instance) is dynamic. It is resolved with Unity.

It all works well before I tried to change to delegate:

// The declaration
public delegate bool ServiceMethod(object viewModel);

// The magic
var delegate = Delegate.CreateDelegate(typeof(ServiceMethod), service, method);

That gives me an ArgumentException. The service is not an instance, and I think this is the problem. If service was something like var service = new Service() I would probably work.

How do I make that delegate work with an injected instance?





Aucun commentaire:

Enregistrer un commentaire