当前位置: 移动技术网 > IT编程>开发语言>.net > 详细介绍.NET中的动态编译技术

详细介绍.NET中的动态编译技术

2017年12月12日  | 移动技术网IT编程  | 我要评论

实惠app,嵇康四弄,临时校车严重超载

代码的动态编译并执行是一个.net平台提供给我们的很强大的工具用以灵活扩展(当然是面对内部开发人员)复杂而无法估算的逻辑,并通过一些额外的代码来扩展我们已有 的应用程序。这在很大程度上给我们提供了另外一种扩展的方式(当然这并不能算是严格意义上的扩展,但至少为我们提供了一种思路)。

动态代码执行可以应用在诸如模板生成,外加逻辑扩展等一些场合。一个简单的例子,为了网站那的响应速度,html静态页面往往是我们最好的选择,但基于数据驱动的网站往往又很难用静态页面实现,那么将动态页面生成html的工作或许就是一个很好的应用场合。另外,对于一些模板的套用,我们同样可以用它来做。另外这本身也是插件编写的方式。

最基本的动态编译

.net为我们提供了很强大的支持来实现这一切我们可以去做的基础,主要应用的两个命名空间是:system.codedom.compiler和microsoft.csharp或microsoft.visualbasic。另外还需要用到反射来动态执行你的代码。动态编译并执行代码的原理其实在于将提供的源代码交予csharpcodeprovider来执行编译(其实和csc没什么两样),如果没有任何编译错误,生成的il代码会被编译成dll存放于于内存并加载在某个应用程序域(默认为当前)内并通过反射的方式来调用其某个方法或者触发某个事件等。之所以说它是插件编写的一种方式也正是因为与此,我们可以通过预先定义好的借口来组织和扩展我们的程序并将其交还给主程序去触发。一个基本的动态编译并执行代码的步骤包括:

·         将要被编译和执行的代码读入并以字符串方式保存

·         声明csharpcodeprovider对象实例

·         调用csharpcodeprovider实例的compileassemblyfromsource方法编译

·         用反射生成被生成对象的实例(assembly.createinstance)

·         调用其方法

以下代码片段包含了完整的编译和执行过程:

复制代码 代码如下:

//get the code to compile

string strsourcecode = this.txtsource.text;

 

// 1.create a new csharpcodeprivoder instance

csharpcodeprovider objcsharpcodeprivoder = new csharpcodeprovider();

 

// 2.sets the runtime compiling parameters by crating a new compilerparameters instance

compilerparameters objcompilerparameters = new compilerparameters();

objcompilerparameters.referencedassemblies.add("system.dll");

objcompilerparameters.referencedassemblies.add("system.windows.forms.dll");

objcompilerparameters.generateinmemory = true;

 

// 3.compilerresults: complile the code snippet by calling a method from the provider

compilerresults cr = objcsharpcodeprivoder.compileassemblyfromsource(objcompilerparameters, strsourcecode);

 

if (cr.errors.haserrors)

{

    string strerrormsg = cr.errors.count.tostring() + " errors:";

 

    for (int x = 0; x < cr.errors.count; x++)

    {

        strerrormsg = strerrormsg + "\r\nline: " +

                     cr.errors[x].line.tostring() + " - " +

                     cr.errors[x].errortext;

    }

 

    this.txtresult.text = strerrormsg;

    messagebox.show("there were build erros, please modify your code.", "compiling error");

 

    return;

}

 

// 4. invoke the method by using reflection

assembly objassembly = cr.compiledassembly;

object objclass = objassembly.createinstance("dynamicly.helloworld");

if (objclass == null)

{

    this.txtresult.text = "error: " + "couldn't load class.";

    return;

}

 

object[] objcodeparms = new object[1];

objcodeparms[0] = "allan.";

 

string strresult = (string)objclass.gettype().invokemember(

           "gettime", bindingflags.invokemethod, null, objclass, objcodeparms);

 

this.txtresult.text = strresult;

需要解释的是,这里我们在传递编译参数时设置了generateinmemory为true,这表明生成的dll会被加载在内存中(随后被默认引用入当前应用程序域)。在调用gettime方法时我们需要加入参数,传递object类型的数组并通过reflection的invokemember来调用。在创建生成的assembly中的对象实例时,需要注意用到的命名空间是你输入代码的真实命名空间。以下是我们输入的测试代码(为了方便,所有的代码都在外部输入,动态执行时不做调整):

复制代码 代码如下:

using system;

namespace dynamicly

{

    public class helloworld

    {

        public string gettime(string strname)

        {

            return  "welcome " + strname + ", check in at " + system.datetime.now.tostring();

        }

    }

}

运行附件中提供的程序,可以很容易得到一下结果:

改进的执行过程

现在一切看起来很好,我们可以编译代码并把代码加载到当前应用程序域中来参与我们的活动,但你是否想过去卸载掉这段程序呢?更好的去控制程序呢?另外,当你运行这个程序很多遍的时候,你会发现占用内存很大,而且每次执行都会增大内存使用。是否需要来解决这个问题呢?当然需要,否则你会发现这个东西根本没用,我需要执行的一些大的应用会让我的服务器crzay,不堪重负而疯掉的。

要解决这个问题我们需要来了解一下应用程序域。.net application domain是.net提供的运行和承载一个活动的进程(process)的容器,它将这个进程运行所需的代码和数据,隔离到一个小的范围内,称为application domain。当一个应用程序运行时,application domains将所有的程序集/组件集加载到当前的应用程序域中,并根据需要来调用。而对于动态生成的代码/程序集,我们看起来好像并没有办法去管理它。其实不然,我们可以用application domain提供的管理程序集的办法来动态加载和移除assemblies来达到我们的提高性能的目的。具体怎么做呢,在前边的基础上增加以下步骤:

·         创建另外一个application domain

·         动态创建(编译)代码并保存到磁盘

·         创建一个公共的远程调用接口

·         创建远程调用接口的实例。并通过这个接口来访问其方法。

换句话来讲就是将对象加载到另外一个appdomain中并通过远程调用的方法来调用。所谓远程调用其实也就是跨应用程序域调用,所以这个对象(动态代码)必须继承于marshalbyrefobject类。为了复用,这个接口被单独提到一个工程中,并提供一个工厂来简化每次的调用操作:

复制代码 代码如下:

using system;

using system.collections.generic;

using system.linq;

using system.text;

using system.reflection;

 

namespace remoteaccess

{

    /// <summary>

          /// interface that can be run over the remote appdomain boundary.

          /// </summary>

          public interface iremoteinterface

          {

                   object invoke(string lcmethod,object[] parameters);

          }

 

          /// <summary>

          /// factory class to create objects exposing iremoteinterface

          /// </summary>

          public class remoteloaderfactory : marshalbyrefobject

          {

                   private const bindingflags bfi = bindingflags.instance | bindingflags.public | bindingflags.createinstance;

 

                   public remoteloaderfactory() {}

 

                   public iremoteinterface create( string assemblyfile, string typename, object[] constructargs )

                   {

                             return (iremoteinterface) activator.createinstancefrom(

                                      assemblyfile, typename, false, bfi, null, constructargs,

                                      null, null, null ).unwrap();

                   }

          }      

}

接下来在原来基础上需要修改的是:

·         将编译成的dll保存到磁盘中。

·         创建另外的appdomain。

·         获得iremoteinterface接口的引用。(将生成的dll加载到额外的appdomain)

·         调用invokemethod方法来远程调用。

·         可以通过appdomain.unload()方法卸载程序集。

以下是完整的代码,演示了如何应用这一方案。

复制代码 代码如下:

//get the code to compile

string strsourcecode = this.txtsource.text;

 

//1. create an addtional appdomain

appdomainsetup objsetup = new appdomainsetup();

objsetup.applicationbase = appdomain.currentdomain.basedirectory;

appdomain objappdomain = appdomain.createdomain("myappdomain", null, objsetup);

 

// 1.create a new csharpcodeprivoder instance

csharpcodeprovider objcsharpcodeprivoder = new csharpcodeprovider();

 

// 2.sets the runtime compiling parameters by crating a new compilerparameters instance

compilerparameters objcompilerparameters = new compilerparameters();

objcompilerparameters.referencedassemblies.add("system.dll");

objcompilerparameters.referencedassemblies.add("system.windows.forms.dll");

 

// load the remote loader interface

objcompilerparameters.referencedassemblies.add("remoteaccess.dll");

 

// load the resulting assembly into memory

objcompilerparameters.generateinmemory = false;

objcompilerparameters.outputassembly = "dynamicalcode.dll";

 

// 3.compilerresults: complile the code snippet by calling a method from the provider

compilerresults cr = objcsharpcodeprivoder.compileassemblyfromsource(objcompilerparameters, strsourcecode);

 

if (cr.errors.haserrors)

{

    string strerrormsg = cr.errors.count.tostring() + " errors:";

 

    for (int x = 0; x < cr.errors.count; x++)

    {

        strerrormsg = strerrormsg + "\r\nline: " +

                     cr.errors[x].line.tostring() + " - " +

                     cr.errors[x].errortext;

    }

 

    this.txtresult.text = strerrormsg;

    messagebox.show("there were build erros, please modify your code.", "compiling error");

 

    return;

}

 

// 4. invoke the method by using reflection

remoteloaderfactory factory = (remoteloaderfactory)objappdomain.createinstance("remoteaccess","remoteaccess.remoteloaderfactory").unwrap();

 

// with help of factory, create a real 'liveclass' instance

object objobject = factory.create("dynamicalcode.dll", "dynamicly.helloworld", null);

 

if (objobject == null)

{

    this.txtresult.text = "error: " + "couldn't load class.";

    return;

}

 

// *** cast object to remote interface, avoid loading type info

iremoteinterface objremote = (iremoteinterface)objobject;

 

object[] objcodeparms = new object[1];

objcodeparms[0] = "allan.";

 

string strresult = (string)objremote.invoke("gettime", objcodeparms);

 

this.txtresult.text = strresult;

 

//dispose the objects and unload the generated dlls.

objremote = null;

appdomain.unload(objappdomain);

 

system.io.file.delete("dynamicalcode.dll");

对于客户端的输入程序,我们需要继承于marshalbyrefobject类和iremoteinterface接口,并添加对remoteaccess程序集的引用。以下为输入:

复制代码 代码如下:

using system;

using system.reflection;

using remoteaccess;

 

namespace dynamicly

{

    public class helloworld : marshalbyrefobject,iremoteinterface

    {

        public object invoke(string strmethod,object[] parameters)

        {

            return this.gettype().invokemember(strmethod, bindingflags.invokemethod,null,this,parameters);

        }

 

        public string gettime(string strname)

        {

            return  "welcome " + strname + ", check in at " + system.datetime.now.tostring();

        }

    }

}


这样,你可以通过适时的编译,加载和卸载程序集来保证你的程序始终处于一个可控消耗的过程,并且达到了动态编译的目的,而且因为在不同的应用程序域中,让你的本身的程序更加安全和健壮。
示例代码下载:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网