重要的是,AssemblyResolve 事件注册发生在您从计划通过该回调加载的程序集中引用任何类型之前。即使您没有在静态构造函数中引用类型,您也必须确保类中没有静态变量,或者它是引用外部程序集中类型的基类。
我是这样做的:我有一个单独的类来处理程序集加载,恰当地命名为 AssemblyLoader:
using System;
using System.IO;
using System.Linq;
using System.Reflection;
internal static class AssemblyLoader
{
internal static void RegisterAssemblyLoader()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve -= OnResolveAssembly;
currentDomain.AssemblyResolve += OnResolveAssembly;
}
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
return LoadAssemblyFromManifest(args.Name);
}
private static Assembly LoadAssemblyFromManifest(string targetAssemblyName)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(targetAssemblyName);
string resourceName = DetermineEmbeddedResourceName(assemblyName, executingAssembly);
using (Stream stream = executingAssembly.GetManifestResourceStream(resourceName))
{
if (stream == null)
return null;
byte[] assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
private static string DetermineEmbeddedResourceName(AssemblyName assemblyName, Assembly executingAssembly)
{
//This assumes you have the assemblies in a folder named "EmbeddedAssemblies"
string resourceName = string.Format("{0}.EmbeddedAssemblies.{1}.dll",
executingAssembly.GetName().Name, assemblyName.Name);
//This logic finds the assembly manifest name even if it's not an case match for the requested assembly
var matchingResource = executingAssembly.GetManifestResourceNames()
.FirstOrDefault(res => res.ToLower() == resourceName.ToLower());
if (matchingResource != null)
{
resourceName = matchingResource;
}
return resourceName;
}
}
然后,在我的插件类中,我使用静态构造函数来调用我的 AssemblyLoader。通过将逻辑移动到单独的类中,我限制了我在插件类的静态上下文中引用的类型的数量,从而降低了我意外引用外部程序集中的某些内容的风险。
using System;
using Microsoft.Xrm.Sdk;
public class MyPlugin : IPlugin
{
static MyPlugin()
{
AssemblyLoader.RegisterAssemblyLoader();
}
public void Execute(IServiceProvider serviceProvider)
{
//...
}
}
我还将外部程序集的几乎所有用法都移到了其他类中,因此我的插件类根本不使用。大多数情况下,这是出于谨慎考虑。