开发者

unexpected result in mef

开发者 https://www.devze.com 2023-03-16 18:34 出处:网络
i am beginner in MEF. i write this code but i cant understand why program show this result. namespace ConsoleApplication1

i am beginner in MEF. i write this code but i cant understand why program show this result.

namespace ConsoleApplication1
{
    public class MEFTest
    {
         [Import]
        public string Text { get; set; }

        [Import]
        public IExtension Ext { get; set; }

        public void ShowText()
        {
            AssemblyCatalog asscatalog = new AssemblyCatalog(开发者_JS百科typeof(Extension2).Assembly);
            CompositionContainer container = new CompositionContainer(asscatalog);

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(this);

            container.Compose(batch);

            Console.WriteLine(Text);
            Console.WriteLine(Ext.Text);
        }
    }
    class Program
    {
        static void Main( string[] args )
        {
            MEFTest mef = new MEFTest();

            mef.ShowText();

            Console.ReadKey();
        }
    }

    public interface IExtension
    {
        string Text { get; set; }
    }

    [Export]
    public class Extension1 : IExtension
    {
        [Export]
        public string Text { get; set; }

        public Extension1()
        {
            Text = "From Extension1.";
        }
    }

    [Export(typeof(IExtension))]
    public class Extension2 : IExtension
    {
       // [Export(typeof(IExtension).GetProperties()[0].GetType())]
        public string Text { get; set; }

        public Extension2()
        {
            Text = "From Extension2.";
        }
    }
} 

result :

From Extension1. From Extension2.


This is just how MEF is matching your imports. Since you have:

    [Import]
    public string Text { get; set; }

In this case, MEF finds a "string Text" and does the match. This happens from Extention1, but only because you explicitly added an export to its Text property.

    [Import]
    public IExtension Ext { get; set; }

This finds the actual Export of type IExtension. The only one of these is your Extension2 class. This fulfills this requirement.


Extension1 declares that it exports itself (type Extension1, not the interface) and exports a property named Text of type string.

In composition, this will be bound to the Text property tagged as import.

Extension2 declares that it exports type IExtension. This will be bound to the Ext property tagged to import IExtension.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号