I would like to create some existing code-modules (IMyDesiredType
) to load with MEF. The modules mostly have some constructor arguments which I want to provide with MEF (ImportingConstructor
). So far this works fine.
The problem now arises because sometimes the dependencies are not available (they are null) in the host application. The modules will throw by convention an ArgumentNullException
and I don’t want to change that. However I want MEF to overlook such objects (not include them in the object-graph).
[Export(typeof(IMyDesiredType))]
class MyModule : IMyDesiredType{
[ImportingConstructor]
public MyModule(object aNecessaryDependency){
if(aNecessaryDependency==null) throw new ArgumentNullException(nameof(aNecessaryDependency))
}
}
To acquire this, I let MEF create Lazy<IMyDesiredType>
instances and the initializing them one by one.
foreach(var myLazy in collectionOfMefExports){
try{
myLazy.Value // do something with the value, so the object gets composed
}catch(CompositionException){
// Here I get the ArgumentNullException wrapped in a CompositionException
// and also can work around it. However because of the exception handling
// is on the first hand in MEF, VS will break always in the throwing
// constructor of the module
continue; // Go to the next module after logging etc.
}
}
The problem here is, that I have to catch CompositionException
and not directly the Exception
(mostly ArgumentNullException
) from the module's constructor. Therefore, Visual-Studio breaks on each module, because of the Exception is not catched from user-code. The obvious solution to this is, to tell visual studio not to break on ArgumentNullException
-types, but this feels very “hackish” to me. And in any other place, I want VS to break on ArgumentNullException
s.
Is there another pattern with which I can make MEF not to add components to the graph, where the dependency is declared ([Export]
), but it’s value is null, or is there a method of a MEF-class I can override in a derived class and catch the constructor-exception on the fore-hand?
Please leave a comment, if the question is not clear, I'm not a native english speaker and therefore maybe the quesion is verbalized a litte confusing.
[DebuggerHidden]
and[DebuggerStepThrough]
attributes as the answers there suggests? #1420890 – Magdeburg