【问题标题】:Generating DLL assembly at run time and change it?在运行时生成DLL程序集并改变它?
【发布时间】:2016-10-26 14:11:41
【问题描述】:

我创建了一个 dll,其中包含一个名为 PersonVM 的类,如下所示。及其工作...

  public ActionResult Index()

    {


        using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
        {
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = "Per.dll";
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, "public class PersonVM{ " + "public int id{get;set;}" +
                "public string Name{get;set;}" + "public string LName{get;set;}" + " }");
        }

        Assembly assembly = Assembly.LoadFrom("Per.dll");
        var type = assembly.GetType("PersonVM");
        var d = type.GetProperties();
        object obj = Activator.CreateInstance(type, true);
        return View(obj);


    }

但是这段代码在我的索引控制器中只运行一次。 例如,它不会在这里更改我的 dll 类:

     public ActionResult Conf()

    {
        using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
        {
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = "Per.dll";

            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, "public class PersonVM{ " + "public int id{get;set;}" +
              "public string Name{get;set;}" + "public string LName{get;set;}" + "public string LNamee2 { get; set; }" + "public string L4 { get; set; }" + " }");
        }


        Assembly assembly = Assembly.LoadFrom("Per.dll");
        var type = assembly.GetType("PersonVM");


        object obj = Activator.CreateInstance(type, true);



        List<ClassInfoVM> model = obj.GetType().GetProperties()
            .Select(T => new ClassInfoVM()
            {
                PropName = T.Name,

                TypeOfProp = T.PropertyType.Name

            }).ToList();


        return View(model);
    }

没有任何错误..它只是不改变我的 dll 类...dll 类PersonVM 只是包含我设置它的属性,第一次在Index

【问题讨论】:

  • 出于好奇,您为什么要在运行时构建这些类?
  • 感谢您的评论。我实际上想使用这个类作为我的视图模型......这意味着我想让用户自己动态地提供视图模型和模型。在 mvc 中使用 EntityFramework

标签: c# dll reflection asp.net-mvc-5 csharpcodeprovider


【解决方案1】:

您不能使用Assembly.LoadFrom 在应用程序域中加载同名 DLL 两次。

参见MSDN上Assembly.LoadFrom函数的the Remarks section

LoadFrom 方法有以下缺点。考虑使用 Load 代替。

  • 如果已加载具有相同标识的程序集,即使指定了不同的路径,LoadFrom 也会返回加载的程序集。

一种可能的解决方案是让CSharpCodeProvider 为程序集生成一个随机名称并加载它,但是如果我在你那里我会认真考虑你是否真的需要在运行时构建这些类。只需在设计时构建它们并给它们两个不同的名称。甚至可能使版本 conf Conf 派生自 Index 中的版本

【讨论】:

  • 我尝试了 Assembly.Load 但我得到:“无法加载文件或程序集 'Per, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' 或其依赖项之一。系统找不到指定的文件。”
猜你喜欢
  • 2010-10-10
  • 2012-07-14
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多