This project has moved and is read-only. For the latest updates, please go here.

ExportFactory from arbitrary Type

Jun 13, 2010 at 10:07 PM

I see how to use the ExportFactory<T> to create new instances of an exported type, when the type (T) is known.

I'm wondering, what is the approach when you don't know what T is, and you have an arbitrary Type object to construct from.

This is in a place in my code, where typically I do something like this:

                var viewModel = Activator.CreateInstance(type);

However (1) that's not good when I'm using MEF, and (2) only works when the type refers to the concrete instance, not an abstract interface.  So I'd like to be able to tell MEF, "please resolve one of these T's, which is probably an interface:.

How do I do that?


Jun 14, 2010 at 6:04 PM

To answer your question directly the only way to resolve with an arbitrary Type from a Type object is to query the container directly container.GetExports(Type type, Type metadataView, string contractName) (a call like container.GetExports(type, null, null) will work in most cases). You cannot get an ExportFactory back from a direct query on the container and you will also have to query it as a collection because that is the inner most call and the only one that takes an arbitrary Type object.

Now for a observation, I can understand if you wanted to do this for a generalized helper type but for a specific object I would be hesitate to use this pattern and I would hope they would know at least the abstract type they are interested in at compile time. In general we don't like every object having direct access to the container because it hampers there reusability. The host object is generally the only object that has direct access to the container.