Dave
Dave

Reputation: 1925

How to convert object to correct type

I have the following code that resolve a service using the non generic method. I can not use the generic one that would have solved my issue because I don't know upfront the type that are going to be passed in.

I don't like the very last line, it works well but I was wondering if I can "Cast" my handler to the right interface in order to call directly the Handle method ? In my case I know for sure that the type returns by resolve is going to be of type handlerType .

var handlerType = typeof (IQueryHandler<,>).MakeGenericType(query.GetType(), typeof (TResponseData));
var handler = _container.Resolve(handlerType);
var resp = new Response<TResponseData>();
resp.Data =  (TResponseData) handler.GetType().GetMethod("Handle").Invoke(handler, new object[] {query});

Upvotes: 0

Views: 142

Answers (1)

cuongle
cuongle

Reputation: 75306

If you don't like the last using reflection, you can take advantage of dynamic keyword:

var handlerType = typeof (IQueryHandler<,>)
                       .MakeGenericType(query.GetType(), typeof (TResponseData));
dynamic handler = _container.Resolve(handlerType);
var resp = new Response<TResponseData>();
resp.Data =  (TResponseData) handler.Handle(query);

Upvotes: 3

Related Questions