从MVC中的DLL导入方法

时间:2018-09-12 09:25:13

标签: asp.net-mvc mef

我想从MVC中的.dll文件导入方法,并在Controller的操作中运行它们。是否可以使用MEF?是的,我应该如何进行?

1 个答案:

答案 0 :(得分:1)

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