MEF ComposeParts。如何处理插件异常 [英] MEF ComposeParts. How to handle plugin exceptions

查看:736
本文介绍了MEF ComposeParts。如何处理插件异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在网上搜索一个解决方案,但我没有发现任何东西。

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

在我的C#应用​​程序我使用MEF实现插件的模式。一切工作正常。不过今天我试图找出如果一个插件构造函数抛出异常由于某种原因,会发生什么情况。

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.

要载入我使用 CompositionContainer.ComposeParts 插件。如果由于某种原因在X插件之一抛出一个异常,则此方法将失败,什么都不会被加载。

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?

感谢你在前进。

推荐答案

我猜你调用 CompositionContainer.ComposeParts(本),其中有一个类似的特性:

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

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

这意味着,当你调用 ComposeParts ,所有的插件'的构造函数将被调用。或者,你可以采取延迟加载的优势,这将推迟构造函数调用当你真正使用的插件

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

这篇关于MEF ComposeParts。如何处理插件异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆