最近用到了App_Code文件夹,想要实现动态编译文件的方式,即替换文件夹中的类文件从而达到实时修改代码的效果,类似web.config,网上查到的资料基本都是把文件夹中的类文件修改属性为"编译",这跟我想要的效果不一样,但是不这么做的话在VS中无法调用,想来想去只能使用反射+Expression+缓存的方式来实现了.
研究了几个小时后搞了一个App_Code帮助类
假设App_Code文件夹中有这么一个类
namespace WebTest.App_Code { public static class TestClass { public const string TestConst = "testConst"; public readonly static string TestStaticField = "testStaticField"; public static string TestStaticProperty { get { return "testStaticProperty"; } } public static string TestStaticMethod(string value) { return value; } public static string TestStaticMethod(string value1, string value2) { return value1 + value2; } } }
我想要获取以下内容:
1.常量TestConst的值
2.静态字段TestStaticField的值
3.静态属性TestStaticProperty的值
4.静态方法TestStaticMethod(string value)的调用结果
5.静态方法TestStaticMethod(string value1,string value2)的调用结果
好了,在VS中是无法直接使用的,因为类文件属性未修改为"编译",但是这个类会被动态编译成一个程序集.
App_Code生成的动态程序集可以通过 System.Web.Compilation.BuildManager.CodeAssemblies 拿到(PreApplicationStart阶段无法获取)
public static IEnumerable<Assembly> GetApp_CodeAssemblies() { if (BuildManager.CodeAssemblies != null) { foreach (object item in BuildManager.CodeAssemblies) { Assembly assembly; try { assembly = (Assembly)item; } catch { continue; } yield return assembly; } } }