【问题标题】:How to pass a function to another class using IoC如何使用 IoC 将函数传递给另一个类
【发布时间】:2015-04-11 14:56:11
【问题描述】:

我正在尝试实现控制反转 (IoC) 以开发基于插件的应用程序,该应用程序需要能够在发生某些事情时将数据(例如字符串)传递回我的主 EXE。为了实现这一点,我将Action 传递给DLL,它可以用来将数据发送回EXE。以下代码显示了一个小测试应用程序来解释我的初学者问题:

namespace MainExe
{
    class Program
    {
        [Import(typeof(IDataProvider))]
        public IDataProvider stringProvider { get; set; }

        public void myCallback(string str)
        {
            Console.WriteLine(str);
        }

        public Program()
        {
            try
            {
                AggregateCatalog aggregatecatalogue = new AggregateCatalog();
                aggregatecatalogue.Catalogs.Add(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory));
                CompositionContainer container = new CompositionContainer(aggregatecatalogue);
                container.ComposeParts(this);    
            }
            catch (FileNotFoundException fnfex)
            {
                Console.WriteLine(fnfex.Message);
            }
            catch (CompositionException cex)
            {
                Console.WriteLine(cex.Message);
            }
        }

        void Run()
        {
            if (stringProvider != null)
            {
                stringProvider.SaySomething("myrequest", myCallback);
                Console.ReadKey();
            }
        }

        static void Main(string[] args)
        {
            Program program = new Program();
            program.Run();
        }
    }
}

我的界面如下所示:

namespace DataInterfaceDll
{
    public interface IDataProvider
    {
        void SaySomething(string request, Action<string> callback);
    }
}

这是插件 (DLL),它应该能够将某些内容发送回 EXE(或从执行此操作的 EXE 调用函数):

namespace StringDataDll
{
    [Export(typeof(IDataProvider))]
    public class StringData : IDataProvider
    {
        public void SaySomething(string request, Action<string> callback)
        {
            callback("This is just a test program...");
        }
    }
}

当我运行这段代码时,我在下面的行中得到一个System.Reflection.ReflectionTypeLoadException

container.ComposeParts(this);

谁能告诉我我在这里做错了什么?

【问题讨论】:

  • 可执行文件所在文件夹是否有StringDataDll dll的副本?

标签: c# inversion-of-control mef ioc-container


【解决方案1】:

它通过动态加载 DLL 对我有用。

aggregatecatalogue.Catalogs.Add(new AssemblyCatalog(Assembly.LoadFile("yourpath\StringDataDll.dll")));
aggregatecatalogue.Catalogs.Add(new AssemblyCatalog(Assembly.GetAssembly(typeof(IDataProvider))));

当您将 stringDataDll.dll 复制到主程序的输出文件夹中时,它也适用于 new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory)

确保在主程序的输出文件夹中包含所有 dll 文件。

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2021-01-12
    • 2021-12-18
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多