MEF ComposeParts. How to handle plugin exceptions

强颜欢笑 提交于 2019-12-05 11:54:36

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