Search code examples
c#.netdependency-injectionmefdependency-management

MEF import resolution


Let's say that I have a class with a set of fields marked with [Import] attributes where all these fields prohibit recomposition.

At some moment this class is instantiated using new MyClassWithInjectedFields(...) and all the corresponding dependencies are injected using the MEF framework - nothing serious, only bijective Export-To-Import mapping.

Questions:

  • Is it safe to assume that in this case the values of injected fields will remain the same until the class instance is garbage collected?

  • Or maybe there are some rare / obscure cases when they might get changed implicitly by MEF in runtime? Perhaps, when someone unloads or reloads the assembly used for dependency resolution?

(I am new to MEF and I'm not really sure if there is a way affect the dependency graph in runtime, but, well, there obviously might be).


Solution

  • 1) MEF isn't doing anything special with the GC so the instances will not be GC'ed until there are no more live references to the objects.

    2) If the Imports are not marked as recomposible then MEF will only ever change the values of Imports. You cannot unload\reload an assembly in a running .NET process, you can unload an AppDomain but in doing that you will essentially forcibly kill the object references but MEF doesn't do anything special to reset them.