MVC3 ImportMany on Exporting Controller的构造函数参数

时间:2011-02-10 15:44:09

标签: constructor import asp.net-mvc-3 mef

我有一个使用MEF导出并由Controller工厂加载的控制器。

    [Export(Controller)]
    public class MyController : Controller
    {

        private IRepository MyRepsoitory;

        [ImportMany]
        public IEnumerable<MyImportedItem> TestImportItems {get;set;}

        public MyController([ImportMany]IEnumberable<MyImportedItem> items, [Import]IRepository repository)
        {
            // items here is always null
            // However if I grab the container that the ControllerFactory used and tell it ComposeParts on this the TestImportItems will be filled with 50+ items
            // repository however is instantiated appropriately. 

            GlobalItems.Container.ComposeParts(this);
            //Now TestImportItems if filled but my items parameter alway null... how do I get constructor to fill

        }

    }

因此,MEF创建了MyController,但只创建了存储库,并为ImportMany发送了null,即使它稍后可以使用相同的Container填充该属性。

如果我做了一些违反其中一项的事情,MyConroller的创建在ControllerFactory中断了,那也很奇怪......好像它检查了构造函数的部分,但从未将它们推送到IEnumerable参数。

我错过了什么?

显然,如果相同的Container适用于.ComposingParts(这个),我可以使用这些部件(我反映了在创建Controller时可用的相应导入/导出部件的目录。

我可以重写我的类来使用填充的Property但是我真的希望我的导入构造函数能够获得一个填充的集合。

更新:

如果我为导入添加一个简单的包装类,许多MEF将加载[ImportMany]参数。

所以以下内容将为我填充IEnumerable ......

public MyController(TestImportClass test, [Import]IRepository repository)
{
    //test.Items != null
}

public class TestImportClass
{

    public IEnumberable<MyImportedItem> Items {get;set;}

    [ImportingConstructor]
    public TestImportClass([ImportMany]IEnumberable<MyImportedItem> items)
    {
        this.Items = items;
    }
}

我在实际代码中使用“约定”系统来标记Controller for Export。可能由于某些原因导致MEF无法理解导入初始构造函数参数?如果是这种情况虽然我不确定为什么我的IRepository总是被填满?

2 个答案:

答案 0 :(得分:0)

调用ComposeParts时,传递已构造的对象。在现有对象上再次调用构造函数是不可能的。 (在这种情况下,如果你这样做,你最终会得到无限递归)。因此ComposeParts不满足构造函数导入。

如果您的控制器是以其他方式从容器中拉出来的,并且在构造函数上放置了ImportingConstructorAttribute,则应该满足构造函数的导入。

答案 1 :(得分:0)

您正在使用的约定系统可能不支持构造函数参数中的ImportMany。据推测,该约定不适用于TestImportClass,这就是ImportMany在该构造函数上工作的原因。

我们计划在下一版本的MEF中提供官方会议模型支持,我们应该发布新的codeplex版本,并尽快预览此支持。