Wednesday, December 12, 2012

Simple MEF (Dependency Injection) example for Web Application

We need create 3 components:


1. Class that going to use imports of instances:


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

public class MainPagesRouteHandler : IRouteHandler
{
    [Import(typeof(ILoggingManager))]
    public LoggingManager LoggingManager;
    public void DoImport()
    {
         var directory = AppDomain.CurrentDomain.BaseDirectory;
         var path = System.IO.Path.Combine(directory, "bin");
         var catalog = new DirectoryCatalog(path);
         var container = new CompositionContainer(catalog);
         container.ComposeParts(this);
    }
    protected void Page_Load(object sender, System.EventArgs e)
    {
         DoImport();

         LoggingManager -has been imported!
    }
}
 

2. Class that will be injected instance:

using System.ComponentModel.Composition; 
 
namespace BroadwayBox.Logging
{
    [Export(typeof(ILoggingManager))]
    public class LoggingManager : ILoggingManager
    {
        public string Title { getset; }
    }
}


3. Injected class Contract (Interface)

namespace BroadwayBox.Logging.Contracts
{
    public interface ILoggingManager
    {        
        void WriteLog();
    }
}