user7359612
user7359612

Reputation: 13

MEF Import has Nothing

I want to use mef to add plugins. And in the plugin, has something imported from other plugin added by main program, just like ioc?

now I can get this plugin successfully, but in the plugin can not get the imported one.

Following is my code. the log in plugin.Service is null.

Interfaces Project

Ilog.cs

public interface Ilog
{
    void Log(string log);
}

IServece.cs

public interface IService
{
    Ilog Log { get; }

    void DoSomeThing();
}

IPlugin.cs

public interface IPlugin
{
    string PluginName { get; }

    IService Service { get; }
}

Plugin1 Project

public class Plugin1Service : IService
{
    [Import(typeof(Ilog))]
    public Ilog Log { get; private set; }//todo:Log is null

    public void DoSomeThing()
    {
        Log.Log("test from Plugin1");
    }
}

[Export(typeof(IPlugin))]
public class Plugin1Info : IPlugin
{
    public string PluginName => "Plugin1";

    public IService Service =>new Plugin1Service();
}

ConsoleLog Porject

[Export(typeof(Ilog))]
public class Console1 : Ilog
{
    public void Log(string log)
    {
        Console.WriteLine(log);
    }
}

Main Project

class Program
{
    static void Main(string[] args)
    {
        var catalogs = new DirectoryCatalog(Directory.GetCurrentDirectory());
        var container = new CompositionContainer(catalogs);

        var plugin = container.GetExportedValue<IPlugin>();
        Console.WriteLine($"{plugin.PluginName}");
        plugin.Service.DoSomeThing();

        Console.ReadKey(true);
    }
}

when run the program, the log in plugin.Service is null (can see 'todo:') . How can I get the log item?

Upvotes: 1

Views: 228

Answers (1)

Pidon
Pidon

Reputation: 275

You create your own service instance, so MEF does not provide an ILog instance.

When you let MEF create your service it will pick up on the Log property. So:

    [Export(typeof(IService))] // Add this export
    public class Plugin1Service : IService
    {
        [Import(typeof(Ilog))]
        public Ilog Log { get; private set; }//todo:Log is null

        public void DoSomeThing()
        {
            Log.Log("test from Plugin1");
        }
    }

    [Export(typeof(IPlugin))]
    public class Plugin1Info : IPlugin
    {
        public string PluginName => "Plugin1";

        [Import] // Import the service
        public IService Service { get; set; }
    }

In case you HAVE to create the service yourself you can ask MEF to fill out all imports by calling SatisfyImportsOnce on the CompositionContainer.

Upvotes: 1

Related Questions