【问题标题】:Change .dll in runtime在运行时更改 .dll
【发布时间】:2013-10-01 12:10:38
【问题描述】:

我有一个庞大的应用程序,我的解决方案的一个项目可以生成报告。 我想添加新报告(更新报告)而不构建我的项目,只需添加.dll 文件。我读到了AssemblyAppDomain,但我不知道为新报告添加新 dll 以及如何在运行时更新旧报告是否真的很好? 这是我的示例,它需要我的第一个 dll,但第二次不需要。第一个 dll - 总和,第二个 - 扣除。

    static void Main(string[] args)
    {
        try
        {
            //first domain
            AppDomain domain = AppDomain.CreateDomain("MyDomain");
            AssemblyDll asb1 = new AssemblyDll();
            Console.WriteLine(asb1.AssemblyMethod(1));
            AppDomain.Unload(domain);
            Console.ReadKey();

            //second domain
            AppDomain newDomain = AppDomain.CreateDomain("myNewDomain");
            AssemblyDll asb2 = new AssemblyDll();
            Console.WriteLine(asb2.AssemblyMethod(2));
            AppDomain.Unload(newDomain);
            Console.ReadKey();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

public class AssemblyDll
{
    public string AssemblyMethod(int version)
    {
        //loading .dll
        Assembly assembly = Assembly.LoadFrom(@"../../../../Assembly/DynamicDLL" + version + ".dll");
        Type type = assembly.GetType("DynamicDLL.Dynamic");
        object instance = Activator.CreateInstance(type);
        MethodInfo[] methods = type.GetMethods();
        //invoke method
        object result = methods[0].Invoke(instance, new object[] { 5, 3 });
        return result.ToString();
    }
}

我的 .dll 文件来自:

namespace DynamicDLL
{
    public class Dynamic
    {
        public int DynamicMethod(int a, int b)
        {
            return a + b;
            //return a - b;
        }
    }
}

【问题讨论】:

  • 您的代码在我的机器上运行良好。
  • 真的给出不同的结果吗?对我来说,它给出了 2 和 2(应该是 8)...
  • 可能是我用.net 4.5运行的,你用的是哪个版本?

标签: c# .net dll


【解决方案1】:

如果你想写类似插件的东西,喜欢插件的方法,你应该看看 MEF http://msdn.microsoft.com/en/library/vstudio/dd460648.aspx

MEF 允许您动态使用任何程序集,甚至可以将 dll 放入文件夹并从中构建 MEF 目录。

实际上是 Visual Studio 并在内部使用 MEF 来实现可扩展性(插件...)

【讨论】:

  • 我知道 MEF 是在 .net 4.0 中使用的,您认为 .net 3.5 版本会如何?
  • 是的,如果您下载预览版 9 并自己编译它应该是可能的。虽然没有正式发布
【解决方案2】:

程序集通常加载到AppDomain 一次,一旦加载就无法卸载。

您可以创建一个新的AppDomain 并将您的程序集加载到其中,当您释放它时,程序集将被卸载。但是需要注意的是,您不能直接在两个 AppDomain 之间进行通信,您必须使用远程处理等其他方法在两者之间进行编组。

关于插件和使插件无法加载的文章很多,谷歌快速搜索显示了这些:

http://www.brad-smith.info/blog/archives/500

http://adrianvintu.com/blogengine/post/Unloadable-plugins.aspx

希望这些对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 2011-04-10
    • 2011-01-01
    • 2010-12-05
    相关资源
    最近更新 更多