views:

68

answers:

2

Using information from some of the questions here on generic views, I have created an MVC app that reads .dlls from its own /bin directory and builds the UI on the fly. InputBuilder partial views helped a lot. I also made a ControllerFactory, after the advice from here and elsewhere.

My problem is, while everything is working OK and reflection is recognizing the types I'm passing around, GetType() requires the full assembly qualified name ('scuse the code, still prototyping):

public IController CreateController(RequestContext requestContext, string controllerName)
        {
            Type controllerType = null;
            Type genericType;

            //controllerName coming in as full assembly-qualified path

            Type baseControllerType = typeof(CoreDataController<>);

                genericType = Type.GetType(controllerName);
                if (genericType != null)
                { 
                    controllerType = baseControllerType.MakeGenericType(genericType); 
                }
            if (controllerType != null)

            { 
                return Activator.CreateInstance(controllerType) as IController; 
            }

            return controllerType;

        }

This makes my urls look like this:

http://localhost:1075/CoreData.Plans,%20PlansLib,%20Version=1.0.0.0,%20Culture=neutral,%20PublicKeyToken=null/Create

Obviously sub-optimal.

What I'd like is http://localhost:1075/CoreData.Plans/Create

or even better:

http://localhost:1075/Plans/Create

Should I store a dictionary accessible to my controller on Application_Start() mapping short names to fully-qualified names? Is there a feature of Reflection I'm missing that would solve this problem?

A: 

I think your idea of a dictionary mapping pretty names to types would be good. You may want to try putting attributes on your classes, then at startup, you can use reflection to extract out the attributes for building the dictionary:

[UrlName("my-class-name")]
public class MyClassName
{
    // ...
}
Jacob
went with the dictionary approach, made it a static field on the ControllerFactory, it's working great.
Chris McCall
A: 

I had this problem with long and even inconsistant type names across different platforms that i was using and came up with a way to search for the type in the dlls loaded in the current appdomain.

public static Type GetTypeFromName(string TypeNameStr, Assembly[] Asms)
{
 Type VarType = null;
 string TypeStr = TypeNameStr.Split(',')[0];
 foreach (Assembly Dll in Asms)
 {
  VarType = Dll.GetType(TypeNameStr);
  if (VarType == null)
   VarType = Dll.GetType(TypeStr);
  if (VarType != null)
   break;
 }
 return VarType;
}

All that you need to do is pass the function a list of assemblies that you can get from the current appdomain and it will try to find the Type from there you can create a dictionary using the name and the type to cache this so that you don't have to do this over and over again.

scptre