views:

247

answers:

2

Platform: C# 2.0 WinForms

I have a factory class that provides an instantiation of a particular data mapper depending on the type that I send it, the code is as such:

public static IDataMapper<T> GetMapper<T>() where T: IDto
{
    Type mapperType = MapperLocator.GetMapper(typeof(T));

    return (IDataMapper<T>)mapperType.Assembly.CreateInstance(mapperType.FullName);
}

I am using DynamicProxy2 to intercept method calls to my DTO objects. In my intercept method I am trying to call the above factory using the type from Invocation.TargetType. However this comes back with the exception:

The type or namespace name 'invocation' could not be found.

Obviously this is because any calls to a generic method need to know the type explicitly from what I understand at compile time. Obviously I can't do that in this case and I definitely am not going to do a switch statement across all of my DTO objects.

So, can you guys suggest a strategy or point out what I am doing wrong? I am trying to make this as generic as possible so that it could fit across all of my objects and any new ones as well as code portability to other projects.

Thanks in advance!

A: 

There is no way out of this, unfortunately; the .NET C# compiler needs to know the Type at compile time for generics; you'll have to find another method.

You could perhaps use boxing/unboxing and non-generics, but I do not know much about how you would implement this. Alternatively, you could use System.Reflection. Again, I do not know how to do this.

Callum Rogers
+3  A: 

I'm not familiar enough with DTO to know whether or not there's enough information here for a full solution. That said, another answer is mostly correct; the C# compiler needs type information at compile time.

There is, however, a way around this: reflection. System.Reflection (particularly MethodInfo in your case I think) will allow you to write a fully generic solution.

If I've understood the question correctly, what you'd do is get the MethodInfo for that factory function, substitute in the type with MakeGenericMethod, and then Invoke that.

RAOF
You're a genius! Thank you sir!
joshlrogers