MEF从目录加载插件

jul*_*lia 10 c# location mef .net-assembly

我与MEF合作,我正在寻找如何通过MEF找到插件的另一种方式更改插件位置的URL,我想更改此行

Assembly.LoadFrom(@"C:\julia\project\project.Plugin.Nav\bin\Debug\NavPlugin.dll")));
Run Code Online (Sandbox Code Playgroud)

我想删除此URL,因为我需要在另一台机器上部署我的应用程序

这是我的功能:

public void AssembleCalculatorComponents()
{
   try
   {
       //var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
       //var container = new CompositionContainer(catalog);
       //container.ComposeParts(this);
       var catalog = new AggregateCatalog();

       catalog.Catalogs.Add(new AssemblyCatalog(Assembly.LoadFrom(@"C:\yosra\project\project.Plugin.Nav\bin\Debug\NavPlugin.dll")));
       var container = new CompositionContainer(catalog);

       container.ComposeParts(this);
    }
    catch (Exception ex)
    {
       throw ex;
    }
 }
Run Code Online (Sandbox Code Playgroud)

你能帮我么?

谢谢

Cal*_*ebD 16

您可以使用DirectoryCatalog类让MEF扫描特定目录以查找满足导入的程序集.

var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog("."));
var container = new CompositionContainer(catalog);
Run Code Online (Sandbox Code Playgroud)

上面将添加AppDomain用于定位程序集的基本目录(通常是保存可执行文件的目录,除非通过配置更改)到聚合目录.您可能还想添加当前正在执行的程序集,但这不是必需的.

var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
catalog.Catalogs.Add(new DirectoryCatalog("."));
var container = new CompositionContainer(catalog);
Run Code Online (Sandbox Code Playgroud)

有关DirectoryCatalog的MSDN的更多信息:http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog.aspx


jul*_*lia 5

您好再次感谢您的回复,所以我的问题是直接加载插件,所以我创建了一个目录,我将我的插件放在这个文件夹中,所以我找到了这个解决方案

public void AssembleCalculatorComponents()
        {


            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
            Console.WriteLine(path);
            //Check the directory exists
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            Console.WriteLine(path);
            string assemblyName = Assembly.GetEntryAssembly().FullName;
            Console.WriteLine(assemblyName);
            //Create an assembly catalog of the assemblies with exports
            var catalog = new AggregateCatalog(
                new AssemblyCatalog(Assembly.GetExecutingAssembly().Location),
                new AssemblyCatalog(Assembly.Load(assemblyName)),
                new DirectoryCatalog(path, "*.dll"));

            //Create a composition container
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
Run Code Online (Sandbox Code Playgroud)

这是我的解决方案,为所有人思考