Design-Time Type Resolution

Have you ever wondered how the DataSet component on the ToolBox in VS.NET discovers the strongly-typed data-set instances which are part of your project or its direct references? Not only was I curious, but I also needed that functionality on a designer code that I was writing. Here is what I found.

In the case of the DataSet component, it actually uses a custom ToolboxItem class to allow you to change what type of data-set actually ends up on the design surface. When it pops the dialog it looks at the code in the current project using an underlying feature of the VS.NET system called the CodeModel. It walks the code model looking for the various strongly-typed data-sets and presents them as options for the developer to select.

The ITypeResolutionService service is then used to get a Type instance back from the fully qualified name of the type determined by walking the CodeModel. If it returns null then it generally means it hasn’t been compiled. Referenced assemblies are a little bit different – the path names to the assembly files can be got at using DTE but you can’t just load the assemblies up and suck out the types to inspect them. That would result in the assemblies being loaded into the DefaultDomain setup by VS.NET and the assemblies would be locked until you shutdown the IDE. When getting referenced assembly type information you need to start up a seperate app domain for a short period of time and load all the assemblies into it. You can then get the type information out and unload the domain when done.

All in all it was an interesting tour through some of the VS.NET plumbing. Unfortunately many of the pieces of the puzzle are marked internal so you can reuse them (without resorting to hackery). Since I needed the same functionality I put together a pair of classes which can be dropped into your designer projects which will allow you to get an array of Type instances back given a base-type.

Personally I’d like to see a ITypeResolutionService2 interface defined which would allow me to do this easily without having to write this code. I suspect that the chap who wrote the DataSet designer code would have liked that too!

3 thoughts on “Design-Time Type Resolution

  1. Austin Higgs

    I am writing a generic SQL DAL that needs the list of classes that inherit from BaseBusinessObject, no matter which assembly they’re defined in…

    this helped! Thanks

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