从MVC中的DLL导入方法

问题描述 投票:0回答:1

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

asp.net-mvc mef
1个回答
1
投票

我终于搞定了。写下这个答案以防万一有人被击中。

接口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项目中)。该类包含链接所有导入和导出的函数。

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

最后从Controller调用此方法

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

        public ActionResult Index()
        {
            ViewBag.Message = p.plugin.Work("test input");
            return View();
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.