MEF ComposeParts. How to handle plugin exceptions

独自空忆成欢 提交于 2020-01-13 11:26:46

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/25162234/mef-composeparts-how-to-handle-plugin-exceptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!