Slevin
Slevin

Reputation: 191

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.

Upvotes: 5

Views: 1323

Answers (2)

testalino
testalino

Reputation: 5678

I found that switching from ImportMany to Import and then basically creating a CompositionContainer + DirectoryCatalog for each Dll allowed me to easily detect and filter out incompatible plugins.

It was also not noticably slower than calling compose on multiple catalogs at once.

Upvotes: 0

Adi Lester
Adi Lester

Reputation: 25211

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
        }
    }
}

Upvotes: 5

Related Questions