Thursday, March 19, 2009

Dynamically call a Generic method using Reflection

While working on a request to make the Database Logging add-on I discussed previously, I came accross an interesting problem.

I wanted to be able to define the name of the ExpressionGroup, stored procedure and connection to use when logging to the database in a config file. I figure this was the first step in enabling configuration to the system. In order to do this I needed to create an instance of Expression<T>.

The expression cache already has a CreateGroup<T>() method which I wanted to use. So how can I call this method if I don't know the type of T until runtime? Its actually very easy.

Essentially you want to get a reference to the Method via Reflection. There are lots of ways to do this. Once you have a MethodInfo class, you can call MakeGenericMethod which takes a parameter array of type objects. It will use these type objects to subsitute in place for the Generic type T.

At this point you can call the method just like any other method via reflection, using the Invoke() method on MethodInfo. The code looks like this:

var meth = this.GetType().GetMethod("CreateGroup");

var genericMeth=meth.MakeGenericMethod(getType(grpConfig.AuditLogEntryType));

IAuditLoggerExpressionGroup expGroup = (IAuditLoggerExpressionGroup)genericMeth.Invoke(this, new object[] { grpConfig.Name, grpConfig.ConnectionName, grpConfig.Procedure });


That's all there is to it.

No comments: