Search code examples
.netc#-4.0exceptionpluginsmef

MEF ComposeParts. How to handle plugin exceptions


I have searched on the web for a solution, but I didn't find anything.

In my C# application I am using MEF for implementing a plugin pattern. Everything is working fine. However today I have tried to figure out what happens if a 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?

Thank you in advance.


Solution

  • I'm guessing you're calling CompositionContainer.ComposeParts(this), where this has a property similar to this:

    [ImportMany]
    public IPlugin[] Plugins { get; set; }
    

    which means that when you call ComposeParts, all plugins' constructors will be called. Alternatively, you could take advantage of lazy loading, which will defer the constructor calls to when you actually use a plugin

    [ImportMany]
    public Lazy<IPlugin>[] Plugins { get; set; }
    

    Then, if you'd like to initialize all plugins, you could 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's constructor
                var plugin = lazyPlugin.Value;
    
                // Do any other initialization here
            }
            catch (Exception ex)
            {
                // Log exception and continue iteration
            }
        }
    }