2017-07-17 164 views
1

我想使用mef來添加插件。並且在插件中,從主程序添加的其他插件導入了一些內容,就像ioc一樣?MEF導入沒有什麼

現在我可以成功獲得這個插件,但是在插件中無法獲得導入的插件。

以下是我的代碼。登錄plugin.Service爲null。

接口項目

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項目

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,項目

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

主項目

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); 
    } 
} 

運行程序時,登錄plugin.Service爲空(可以看'todo:')。我如何獲得日誌項目?

回答

1

您創建自己的服務實例,因此MEF不提供ILog實例。

當你讓MEF創建你的服務時,它會在Log屬性中選擇。所以:

[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; } 
    } 

如果你必須創建自己的服務,你可以問MEF通過在CompositionContainer調用SatisfyImportsOnce填寫所有進口。

+0

坦克@Ponon,我明白了。 – user7359612