C# training day 7 : Dependency injection with MEF
Par Nicolas, mardi 21 juin 2011 à 10:50 :: geek stuff :: #496 :: rss
Dummy example in just one class :
using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Reflection; namespace MEF { class Program { static void Main(string[] args) { MyClassWhereIDoLogging m = new MyClassWhereIDoLogging(); // initializes the MEF "container" InitializeMEF(m); m.myLogger.logStuff("Yes, my logger has been injected !"); } private static void InitializeMEF(object obj) { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); container.ComposeParts(obj); } } class MyClassWhereIDoLogging { [Import (typeof(IMyLogger))] public IMyLogger myLogger { get; set; } } interface IMyLogger { void logStuff(string message); } [Export(typeof(IMyLogger))] class MyLogger : IMyLogger { public void logStuff(string message) { Console.WriteLine("LOGSTUFF XXXXX " + message); } } }
Commentaires
Aucun commentaire pour le moment.
Ajouter un commentaire
Les commentaires pour ce billet sont fermés.