MEF: Impossible to import into other classes?

Edit: Matt, this really solves some (most) of my problems, thanks. Now the only lingering problem is how to do this in WPF? I have a custom part based on UserControl, but in WPF there is no way to do this:

[Import]<my:SomeCustomControl>

therefore, the cascade does not work in this case.

/ Edit


I am having the [Import] problem of various MEF components in my project. Should I use CompositionContainer in every class that I use? In the code below, a null reference exception is thrown in the Helper.TimesTwo () method, but when I call logger.Log () in the Program class, everything works. Any help would be greatly appreciated.

(this will compile and run as a console application).

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Run();
        }

        [Import]
        private ILog logger { get; set; }

        public void Run()
        {
            var catalog = new DirectoryCatalog(".");
            var container = new CompositionContainer(catalog);
            var batch = new CompositionBatch();
            batch.AddPart(this);
            container.Compose(batch);

            logger.Log("hello");
            var h = new Helper();
            logger.Log(h.TimesTwo(15).ToString());
            Console.ReadKey();
        }
    }

    class Helper
    {
        [Import]
        private IDouble doubler { get; set; }

        private Helper()
        {
            // do I have to do all the work with CompositionContainer here again?
        }

        public double TimesTwo(double d)
        {
            return doubler.DoubleIt(d);
        }
    }

    interface ILog
    {
        void Log(string message);
    }

    [Export(typeof(ILog))]
    class MyLog : ILog
    {
        public void Log(string message)
        {
            Console.WriteLine("mylog: " + message);
        }
    }

    interface IDouble
    {
        double DoubleIt(double d);
    }

    [Export(typeof(IDouble))]
    class MyDoubler : IDouble
    {
        public double DoubleIt(double d)
        {
            return d * 2.0;
        }
    }
}
+3
3

, . . , . .

+1

, , , MEF . , Helper , , Helper, .

    [Import]
    public Helper MyHelper { get; set; }

    public void Run()
    {
        var catalog = new DirectoryCatalog(".");
        var container = new CompositionContainer(catalog);
        var batch = new CompositionBatch();
        batch.AddPart(this);
        container.Compose(batch);
        logger.Log("hello");
        logger.Log(MyHelper.TimesTwo(15).ToString());
        Console.ReadKey();
    }

, , " ".

+4

[Import]        
private ILog logger { get; set; }

to

[Import]        
public ILog logger { get; set; }

.

+1

Source: https://habr.com/ru/post/1702540/


All Articles