未调用AssemblyResolve,并且在序列化期间抛出FileNotFoundException

在我的ASP.NET应用程序中,有MyAssembly.CustomIdentity类,.NET运行时尝试序列化该类 。 在序列化期间,它抛出FileNotFoundException抱怨它无法加载MyAssembly

  [SerializationException: Unable to find assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345 System.AppDomain.get_Id() +0 .DoCallBackInDefaultDomain(IntPtr function, Void* cookie) +151 .DefaultDomain.Initialize() +30 .LanguageSupport.InitializeDefaultAppDomain(LanguageSupport* ) +41 .LanguageSupport._Initialize(LanguageSupport* ) +391 .LanguageSupport.Initialize(LanguageSupport* ) +65 [ModuleLoadException: The C++ module failed to load while attempting to initialize the default appdomain.] .ThrowModuleLoadException(String errorMessage, Exception innerException) +61 .LanguageSupport.Initialize(LanguageSupport* ) +113 .cctor() +46 [TypeInitializationException: The type initializer for '' threw an exception.] Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.InitializeEnvironment() +0 Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment..cctor() +809 [TypeInitializationException: The type initializer for 'Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment' threw an exception.] Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.get_IsAvailable() +17 SampleWebApp.Default.Page_Load(Object sender, EventArgs e) in C:\Temp\AzureAdvancedRolesSource\Ex2-StartupTasks\CS\Begin\SampleWebApp\Default.aspx.cs:22 

我搜索并看起来像处理AppDomain.AssemblyResolve事件应该有所帮助。 所以我实现了处理该事件:

 public partial class Default : System.Web.UI.Page { static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) { return typeof(MyAssembly.CustomIdentity).Assembly; } protected void Page_Load(object sender, EventArgs e) { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); // this code throws `FileNotFoundException` // during a serialization attempt bool isAvailable = Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.IsAvailable; } } 

但是我的处理程序没有被调用,在序列化尝试期间我仍然有相同的exception。 如何解决此问题 – 如何让序列化程序找到我的程序集?

该问题可能与以下事实有关:CLR在开始调用方法时尝试查找所有程序集,以便在为AssemblyResolve事件连接事件处理程序之前查找程序集。 要解决此问题,您可以将需要汇编的代码解压缩到单独的方法中,并从Page_Load调用它。

有关更多详细信息,请参阅此博客: AppDomain.AssemblyResolve事件提示