Apr 30, 2009 at 8:26 AM
Edited Apr 30, 2009 at 8:31 AM
In my case I don't want to do anything specific to the type. I just want to call a custom constructor, which can't be part of an interface. To do this I need to know the type to create. So I have no need to do anything specific with the actual type.
public static T GetInstance<T>(string contract, params object parameters)
CompositionContainer container = // Create the container etc.
Export<T> export = container.GetExport<T>(contract);
Type type = export.Definition.Metadata["TheActualType"]; // If that was the name of the metadata key for the type that had the export attribute
T result = (T)Activator.CreateInstance(type, parameters);
This knows nothing about the actual type being created - it just needs to know the exported type, DataService. This allows parameters to be passed to the constructor. Obviously this is not great from a safety perspective and it would be better to locate
the matching constructor and call that however this gives a simple idea of what could be achieved.
Having said all this I can see why you may not want to expose it if people do use it the way you suggest.
I have implemented a solution which uses the metadata approach and this means I can also define the parameters the constructor expects so I am quite happy with that.
Thanks for taking the time to respond - I appreciate it.