I would like to create some existing code modules ( IMyDesiredType ) for loading using MEF. Modules contain basically some constructor arguments that I want to provide with MEF ( ImportingConstructor ). So far, this works great.
The problem now arises because sometimes the dependencies are not available (they are equal to zero) in the host application. Modules will throw by convention ArgumentNullException , and I don't want to change that. However, I want the MEF to miss such objects (without including them in the graph object).
[Export(typeof(IMyDesiredType))] class MyModule : IMyDesiredType{ [ImportingConstructor] public MyModule(object aNecessaryDependency){ if(aNecessaryDependency==null) throw new ArgumentNullException(nameof(aNecessaryDependency)) } }
To get this, I allow MEF to instantiate Lazy<IMyDesiredType> and initialize 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 need to catch a CompositionException , and not directly an Exception (mainly ArgumentNullException ) from the module constructor. Thus, Visual-Studio breaks down on each module, because of an exception, user code is excluded. The obvious solution for this is to tell the visual studio not to break into ArgumentNullException types, but it seems very hacky to me. And elsewhere, I want VS to crash into ArgumentNullException s.
Is there any other template with which I can make MEF not add components to the graph where the dependency is declared ( [Export] ), but its value is null or is there a method of the MEF class that I can override in a derived class and catch an exception designer on the front panel?
Please leave a comment if the question is not clear, I am not a native speaker of English, and therefore, perhaps the question is verbalizing, which is a confusing litch.
c # dependency-injection visual-studio-2015 mef
HCL
source share