[IoC] Using MEF with Winforms

Apr 1, 2011 at 8:49 AM

Hello all,

I am working on a Winforms project and i want to try to implement MEF for property injection. I know that MEF isnt a IoC container but it is possible to accomplish what i want.

I have setup the container correctly and injection works fine. The problem i have is the designer generated code, if an object instance is created MEF is not aware of this and ignores the imports.

The only way i can get DI working in those instances is to make MEF aware with SatisfyImportsOnce. This will result that objects which will be instantiated by designer code have a dependency on the MEF container for invoking SatisfyImportsOne and creating dependencies is something i just want to avoid :)

Is there a best practice? Or would it be better to use a IoC container(windsor, unity) for this purpose?

What is your advice?


Apr 9, 2011 at 4:09 PM

So if MEF (or any IOC for that matter) container doesn't actually construct a given object it doesn't know about that object and thus cannot set Imports on it. For things like designer generated code that constructs objects you really only two choices:

1) Pull the construction out of the designer generated code and Import/Export that guy and on importing it set plug it into your UI hierarchy appropriately.
2) Get a hold of the object instance created by the designer at some later point (usually OnImportsSatisified) call Compose or SatisfyImportsOnce on the object. The biggest problem with this approach is that you need to have access to the container (or at least an ICompositionService).

For some samples like MEFShapes (which is WPF but similar idea), I've went with option 1, but it really depends on your situation.