从 MVC 中的 DLL 导入方法

Importing methods from DLL in MVC

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

我终于让它工作了。写下这个答案以防有人在这里受到打击。

接口 DLL

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

包含所需方法的插件

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

(将其包含在您的主 MVC 项目中)。此 class 包含链接所有导入和导出的功能。

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

终于从您的控制器调用此方法

public class HomeController : Controller
    {
        Program p = new Program();

        public ActionResult Index()
        {
            ViewBag.Message = p.plugin.Work("test input");
            return View();
        }
    }