0

I have multiple implementations of an interface IStartup that I need to resolve from a CompositionContainer. Some implementations have an [ImportingConstructor] whose imports are satisfied by another DLL.

It seems that the default behavior when I container.GetExports<IStartup>() will return all the IStartup implementations that are resolvable and skip those that are not (I understand that most containers work this way). So if a dev forgets to reference an assembly the program will run like nothing is wrong.

How can I detect this condition? I would like to throw an exception if that is the case.

4

1 回答 1

0

一种方法是在合成期间允许默认值,这将允许创建部件,然后在构造函数中检查导入部件的值。如果它是给定类型的默认值,则抛出异常。这是一个示例:

[Export(typeof(IStartup))]
public class StartUpThatDoesNotResolve : IStartup
{
    private SomeDependency _sd;

    [ImportingConstructor]
    public StartUpThatDoesNotResolve([Import(AllowDefault=true)] SomeDependency sd)
    {
        if (Object.Equals(sd, default(SomeDependency))) throw new ArgumentException("sd");

        _sd = sd;
    }

    public void Start()
    {
        Console.WriteLine("{0} started", this.GetType().Name);
    }
}

另一种方法是使用Mefx来诊断故障。您可以编写一个调用Mefx的脚本并检查特定故障的输出。如果您正在应用CI,您也可以添加它。

最后但并非最不重要的一点是,您可以下载 Mefx 的源代码并研究并查看他们如何诊断故障。然后你可以尝试类似的东西。在MEF Preview 9的源代码中,您可以在 Samples/CompositionDiagnostics 下找到它。我从来没有这样做过,所以我不能就这种方法提出一些具体的建议。

于 2013-10-25T10:11:02.583 回答