MEF ComposeParts.如何处理插件异常

Sle*_*vin 4 .net plugins mef exception c#-4.0

我在网上搜索了一个解决方案,但我没有找到任何东西.

在我的C#应用​​程序中,我使用MEF来实现插件模式.一切都很好.但是今天我试图弄清楚如果插件构造函数由于某种原因抛出异常会发生什么.

要加载我正在使用的插件CompositionContainer.ComposeParts.如果由于某种原因,其中一个X插件抛出异常,则此方法将失败并且不会加载任何内容.

有没有办法只捕获单个异常,记录并继续?

先感谢您.

Adi*_*ter 5

我猜你正在打电话CompositionContainer.ComposeParts(this),哪里this有类似这样的财产:

[ImportMany]
public IPlugin[] Plugins { get; set; }
Run Code Online (Sandbox Code Playgroud)

这意味着当你调用时ComposeParts,将调用所有插件的构造函数.或者,您可以利用延迟加载,这将在您实际使用插件时将构造函数调用推迟

[ImportMany]
public Lazy<IPlugin>[] Plugins { get; set; }
Run Code Online (Sandbox Code Playgroud)

然后,如果你想初始化所有插件,你可以有这样的东西,它将记录异常,但不会阻止你加载其他插件:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)