我試圖在.Net中動態創建程序集。但是,我似乎無法弄清楚如何讓CodeBase屬性返回一個值。這裏有一個例子:無法從動態生成的程序集中訪問CodeBase
var assemblyName = new AssemblyName
{
Name = "Whatever",
CodeBase = Directory.GetCurrentDirectory()
};
var assemblyBuilder = AppDomain.CurrentDomain
.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("WhateverModule", "Whatever.dll");
var typeBuilder = moduleBuilder.DefineType("WhateverType", TypeAttributes.Public);
var type = typeBuilder.CreateType();
assemblyBuilder.Save("Whatever.dll");
var codeBase = type.Assembly.CodeBase; // throws the below exception
System.NotSupportedException was unhandled
Message=The invoked member is not supported in a dynamic assembly.
Source=mscorlib
StackTrace:
at System.Reflection.Emit.InternalAssemblyBuilder.get_CodeBase()
at Stupid.Program.Main(String[] args) in C:\Users\Walking Disaster\Documents\Visual Studio 10\Projects\Lingual.Proxy\Stupid\Program.cs:line 25
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
任何人都可以看到我做錯了什麼?
說明:我試圖用一個在運行時生成測試方法的插件來擴展NUnit。它通過獲取一系列Action委託來完成此操作。不幸的是,Reflection已經深入到框架中了,所以我不得不爲每個Action委託放一個方法。當我僅使用NUnitTestMethod類時,這很好,但是當我使用NUnitTestFixture時,它失敗了,因爲它試圖從程序集中讀取CodeBase。我不想創建一個物理組件,但是這個項目卻是一個接一個的妥協。
我對此很害怕。我可能必須這樣做才能完成,然後深入研究NUnit,試圖限制它們嚴重依賴反射所造成的損害。 – 2010-04-10 23:24:54