MEF。如何将winform加载到winform容器中?

时间:2010-10-08 12:02:27

标签: c# .net mef

我决定与MEF2和net3.5一起玩一下,我认为这很容易,但我现在被卡住了。通常我的玩具的想法是我想要形成容器,我将加载表单扩展并显示它们。我做了这个代码

我的扩展名:


using System.ComponentModel.Composition;
using System.Windows.Forms;

namespace MyExtantion
{
    public interface IForm
    {
        void LoadForm(Form form);
    }

    [Export(typeof(IForm))]
    public partial class MyExtantion : Form, IForm
    {
        public MyExtantion()
        {
            InitializeComponent();
        }

        public void LoadForm(Form form)
        {
            MdiParent = form;
            Show();
        }

    }
}

并形成容器


using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System.Windows.Forms;

namespace FormsContainer
{
    public partial class FormContainer : Form
    {
        public FormContainer()
        {
            InitializeComponent();
        }

        private CompositionContainer _container;

        public interface IForm
        {
            void LoadForm(Form form);
        }

        [Import(typeof(IForm))]
        public IEnumerable Forms { get; set; }

        private bool Compose()
        {
            var catalog = new AggregateCatalog(
                new AssemblyCatalog(Assembly.GetExecutingAssembly()),
                new DirectoryCatalog("Extantions"));
            var batch = new CompositionBatch();
            batch.AddPart(this);

            _container = new CompositionContainer(catalog);

            try
            {
                _container.Compose(batch);
            }
            catch (CompositionException compositionException)
            {
                MessageBox.Show(compositionException.ToString());
                return false;
            }

            return true;
        }

        private void FormContainer_Load(object sender, EventArgs e)
        {
            if (Compose())
                foreach (IForm form in Forms)
                {
                    form.LoadForm(this);
                }
        }

    }
}

问题是我无法加载我的豁免并且我有这个错误

  

{“组成保持不变。由于以下错误,更改被拒绝:组合产生了单个组合错误。根本原因如下所示。查看CompositionException.Errors属性以获取更多详细信息。 r \ n \ r \ n1)没有找到与约束'((exportDefinition.ContractName = \“FormsContainer.FormContainer + IForm \”)&&(exportDefinition.Metadata.ContainsKey(\“ExportTypeIdentity \”))匹配的导出&& \“FormsContainer.FormContainer + IForm \”。Equals(exportDefinition.Metadata.get_Item(\“ExportTypeIdentity \”))))'。\ r \ n \ r \ nResulting in:无法设置import'FormsContainer.FormContainer .Forms(ContractName = \“FormsContainer.FormContainer + IForm \”)'部分'FormsContainer.FormContainer'。\ r \ nElement:FormsContainer.FormContainer.Forms(ContractName = \“FormsContainer.FormContainer + IForm \”) - &gt ; FormsContainer.FormContainer \ r \ n“}

我如何用MEF实现它?我做错了什么?

1 个答案:

答案 0 :(得分:3)

您在两个不同的地方声明了IForm接口。 如果您只引用一个使用此代码的接口正常工作。