MEF ComposeParts. How to handle plugin exceptions
I have searched the internet for a solution, but I couldn't find anything.
In my C # application, I am using MEF to implement a plugin pattern. Everything works fine. However, today I tried to figure out what happens if the plugin constructor throws an exception for some reason.
To load plugins I am using CompositionContainer.ComposeParts
. If, for some reason, one of the X plugins throws an exception, this method will fail and nothing will be loaded.
Is there a way to just catch the single exception, log it, and continue?
Thanks in advance.
I assume you are calling CompositionContainer.ComposeParts(this)
where this
has a property like this:
[ImportMany]
public IPlugin[] Plugins { get; set; }
which means that when called, ComposeParts
all plugin constructors will be called. Alternatively, you can take advantage of lazy loading, which will defer calls to the constructor when you are actually using the plugin.
[ImportMany]
public Lazy<IPlugin>[] Plugins { get; set; }
Then, if you want to initialize all plugins, you can have something like this, which will log exceptions, but won't stop you from loading other plugins:
public void InitPlugins()
{
foreach (Lazy<IPlugin> lazyPlugin in Plugins)
{
try
{
// Call the plugin constructor
var plugin = lazyPlugin.Value;
// Do any other initialization here
}
catch (Exception ex)
{
// Log exception and continue iteration
}
}
}