Search code examples
asp.net-mvcmef

Importing methods from DLL in MVC


I want to import methods from .dll files in MVC and run them in a Controller's action. Is it possible using using MEF? Is yes, how should I proceed?


Solution

  • I finally got it working. Writing this answer in case someone gets struck here.

    Interface DLL

    namespace MefContracts
    {
        public interface IPlugin
        {
            String Work(String input);
        }
    }
    

    Plugin which contains the required method

    namespace Plugin
    {
    
        [Export(typeof(MefContracts.IPlugin))]
        public class Mytest:MefContracts.IPlugin
        {
            public String Work(String input)
            {
                return "Plugin Called from dll with (Input: " + input + ")";
            }
        }
    
    }
    

    Program.cs

    (Include this in your main MVC project). This class contains the function which links all the imports and exports.

    namespace MyTest
    {
        public class Program
        {
            private CompositionContainer _container;
    
            [Import(typeof(MefContracts.IPlugin))]
            public MefContracts.IPlugin plugin;
    
            public Program()
            {
                var catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new DirectoryCatalog(@"D:\Temp"));
    
    
                _container = new CompositionContainer(catalog);
    
    
                try
                {
                    this._container.ComposeParts(this);
                }
                catch (CompositionException compositionException)
                {
                    Console.WriteLine(compositionException.ToString());
                }
            }
        }
    }
    

    Finally calling this method from your Controller

    public class HomeController : Controller
        {
            Program p = new Program();
    
            public ActionResult Index()
            {
                ViewBag.Message = p.plugin.Work("test input");
                return View();
            }
        }