使用MEF在默认构造函数中导入对象

时间:2015-07-28 18:03:04

标签: c# .net dependency-injection containers mef

我真的认为这还没有被问到,也不确定是否有人在

之前遇到过这个问题

所以我正在与MEF合作,并有一个类似下面的课程 -

[Export]
public class MyClass : IBase
{

private IEnumberable<IMyAddin> _theAddin;

//Default constructor will NOT be
//used because the ImportingConstructor
//attribute is present.
public MyClass() 
{ 
    foreach (var addin in _theAddin)
        DoSomeVeryImportantWork(addin);
}

//This constructor will be used.
//An import with contract type IMyAddin is 
//declared automatically.
[ImportingConstructor] 
public MyClass([ImportMany]IEnumberable<IMyAddin> MyAddin;) : this()
{
    _theAddin = MyAddin;
}

}

我有一个像下面这样的方法 -

T GetById<T>(Guid id) where T:IBase, new()
{
    var x = new T(); 
    //Do some processing
    return x
}

问题是,因为我正在做一个新的T(),默认构造函数对_TheAddin一无所知并且为null。

以前有人遇到过这个吗?如果问题不明确,请告诉我,我可以提供更多详情。

我尝试从默认构造函数中删除[ImportingConstructor],但它不起作用。如何填充_theAddin?

提前致谢!

编辑: 我也尝试过如下,不起作用 -

[Export]
public class MyClass : IBase
{

[ImportMany]
private IEnumberable<IMyAddin> _theAddin;

//Default constructor will NOT be
//used because the ImportingConstructor
//attribute is present.
public MyClass() 
{ 
    foreach (var addin in _theAddin)
        DoSomeVeryImportantWork(addin);
}


}

1 个答案:

答案 0 :(得分:0)

您可能希望自己创建基础的CompositionContainer,并提供一些静态方法来从中检索对象。您还可以直接公开容器,以便可以从任何地方访问SatisfyImportsOnce(),GetExport()等方法。

注意:您可以删除执行导入的ctor并直接使用[ImportMany]装饰您的私有字段。这样在创建新T()之后,您可以调用yourContainer.SatisfyImportsOnce(your_T_instance)。

有关详细信息,请参阅msdn上的示例。

相关问题