… how to get a generic Type object at runtime

Today I needed to query StructureMap for instances that implemented a type with a generic parameter.  The problem is that I didn’t know the type parameter until runtime.  After a bit of looking through members of Type I came across MakeGenericType(Type[] typeArguments).   Acting on a generic type, MakeGenericType will substitute typeArguments for the type parameters.  Not so sure about performance.

Also worth noting that the instances returned by GetAllInstances are of type object.  In my case, AbstractService<T> inherits from AbstractService which contains the method to execute.  An explicit cast was in order.

An alternative approach would consist of using named instances in StructureMap and querying the container based on the type’s name.  If you fat-finger the instance name during the registration process, you can’t know at compile time.

IController controller;
Type type = typeof (AbstractService<>)
    .MakeGenericType(new Type[] {controller.GetType()});
var instances = ObjectFactory.GetAllInstances(type);
foreach (var instance in instances) {
   ((AbstractService) instance).DoStuff();

~ by Bob Banks on 07/02/2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: