ã¯ããã¦ã®MEF
The Managed Extensibility Framework (MEF) is a new library in .NET that enables greater reuse of applications and components.
ã¨ããã¾ãããã¨ããããDIã³ã³ããã¨èãã¦ããã°OKãæ¢ã«è¨äºã¨ãã¦åãä¸ããã¤ããã§ããããéå»ã«ç´¹ä»ãã¦ããã®ã¯ã
はじめてのUnity - 匣の向こう側 - あまりに.NETな
Unityã§ããããã¨ãMonologueの方でMEFã®ã©ã¤ã»ã³ã¹ãMS-LPLãªã®ã§äºã
ã¨ããã£ãè¨æ¶ãããã¾ãããããã«ã¤ãã¦ã¯æ¹åãããæ¹åãªããã§ãã
ã§ã¯ãç°¡åãªãµã³ãã«ã§MEFãè¦ã¦ã¿ã¾ãããã
ã¾ãã¯ãã¤ã³ã¿ãã§ã¼ã¹ã®å®ç¾©ããã¤ãã®IGreetingã
public interface IGreeting { void Say(string msg); }
次ã«å®è£ ã¯ã©ã¹ã
using System.ComponentModel.Composition; [Export(typeof(IGreeting))] public class GreetingImpl : IGreeting { public void Say(string msg) { System.Console.WriteLine ("[{0}]", msg); } }
注ç®ããç®æã¯ã
[Export(typeof(IGreeting))] public class GreetingImpl : IGreeting
ã§ãExportå±æ§ãä»ãããã¨ã§å ¬éããã¾ãã
æå¾ã«ã¤ã³ã¸ã§ã¯ã·ã§ã³ãããã§ã¯setterã¤ã³ã¸ã§ã¯ã·ã§ã³ã使ãã¾ãã
using System.Reflection; using System.ComponentModel.Composition; public class Host { [Import] public IGreeting Greeting { get; set; } public void Run() { Greeting.Say("Hello"); } public static void Main() { var host = new Host(); var catalog = new DirectoryPartCatalog(); var container = new CompositionContainer(catalog.CreateResolver()); container.AddPart(host); container.Compose(); host.Run(); } }
ããã§ã注ç®ã¯ã
[Import] public IGreeting Greeting { get; set; }
Importå±æ§ãä»ãããã¨ã§Exportå±æ§ãä»ãã¦ããåä¸ã®åã®å®è£ ã¯ã©ã¹ãã¤ã³ã¸ã§ã¯ã·ã§ã³ããã¾ããã¡ãªã¿ã«ä»åã®ãµã³ãã«ã¯ã
- IGreeting.dll
- GreetingImpl.dll
- Host.exe
ãããï¼ã¤ã®ã¢ã»ã³ããªããåºæ¥ã¦ãããHost.exeã¯IGreeting.dllãåç §ãã¦ãã¾ãããGreetingImpl.dllã¯åç §ãã¦ãã¾ãããããã¨ã©ããã£ã¦GreetingImpl.dllãè¦ã¤ãã¦ããã®ã§ããããï¼
å®ã¯ã
var catalog = new DirectoryPartCatalog();
ãã®DirectoryPartCatalogããã½ã§ããã®ã«ã¿ãã°ã使ããã¨ã«ãã£ã¦æå®ãããã£ã¬ã¯ããªå ã®ã¢ã»ã³ããªãæ¤ç´¢å¯¾è±¡ã«ããã®ã§ãããã¡ãªã¿ã«ä»åã¯å¼æ°ç¡ãã®ã³ã³ã¹ãã©ã¯ã¿ãå¼ãã§ããã®ã§ã«ã¬ã³ããã£ã¬ã¯ããªã対象ã«ãªãã¾ããMEFã§ã¯ããã®ãããªã«ã¿ãã°ãè¤æ°åå¨ãã対象ã¢ã»ã³ããªã®æ¢ãæ¹ãè²ã é¸æãããã¨ãåºæ¥ã¾ãã
MEFãã¡ãã£ã¨å¼ã£ã¦ã¿ãææ³ã¨ãã¦ã¯ãçµæ§ä½¿ããããããªæãã§æå¾ ã§ãã
(ä½è«)
ã©ã¤ã»ã³ã¹ã®ä»¶ã®è¨äºã«ä»£æ¿ã¨ãã¦Mono.Addinsãç´¹ä»ããã¦ããã®ã§ãDIã³ã³ããçã«ä½¿ããã¢ããªã®ãã¨Mono.Addionsã調æ»ãã¦ããã®ã§ãããã¢ãã¤ã³ã·ã¹ãã ã¨ããæ¬ãã§ã¯DIã³ã³ããã¨éãªãé¨åãããã¾ããããããããªããã£ããªã©ã¤ãã©ãªã®ããã§ãã¡ãã£ã¨æ±ããã¢ãã¨éãã¾ããã