且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态加载页面类/程序集:在全局命名空间中找不到类型或名称

更新时间:2022-10-22 18:53:37

当尝试从DB加载程序集(使用AssemblyResolve事件)时,我遇到了同样的问题。但是如果从磁盘加载程序集或至少将.dll文件的副本保存在磁盘上的某个位置,似乎可以正常工作。


I am trying to create an ASP.Net Web application that stores it's "content" (ASPX/ASCX and assemblies) somewhere other than the file system (Inside a service, for example) and loads them in dynamically as required.

I have successfully created a VirtualPathProvider that takes care of reading ASPX/Master/ASCX files from alternate locations but I am running into problems when those ASPX pages Inherit a class - ie: when they have code behind.

Thanks to answers in another question I am now successfully able to load the assemblies into the application at run time. But when my the runtime attempts to compile my page I get the following error:

"Compiler Error Message: CS0400: The type or namespace name 'Web' could not be found in the global namespace (are you missing an assembly reference?)"

[System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()] public class default_aspx : global::Web.Code.CodeBehind, System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler

I have boiled down my code to a simple example of what is going wrong so that it is easy for you to see. You can download this code here.

The assembly is being loaded in dynamically at run time using the AppDomain.AssemblyResolve event. This is in the global.asax and looks like this:

protected void Application_Start(object sender, EventArgs e)
{
    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(Assembly_Resolve);
}

Assembly Assembly_Resolve(object sender, ResolveEventArgs args)
{
    Assembly assembly = AppDomain.CurrentDomain.Load(Resources.Web_Code);
    if (args.Name == assembly.FullName)
    {
        return assembly;
    }
    return null;
}

Any ideas?

EDIT If for any reason you need to update the Web.Code assembly - you will need to copy it into the "ReferencedAssemblies" folder of the web project for those changes to take effect.

I encountered the same problem when trying to load assemblies from DB (and using the AssemblyResolve event). But it seems to work fine if you load assemblies from disk or at least save a copy of the .dll file somewhere on the disk.