运行时指令
在运行时,当您不关心存在什么特定版本时,您可以使用它AppDomain.AssemblyResolve
来解决程序集版本控制问题,您只想加载/bin
文件夹中的内容。这段代码是从这里获得灵感而创建的。
string[] ignoreAssembyVersions = new string[] { "log4net" };
AppDomain.CurrentDomain.AssemblyResolve += (_, assembly) =>
{
//ignore the vesion number and return any version that has been loaded
var name = new AssemblyName(assembly.Name);
var shortName = name.Name; // retrieve short name
if (ignoreAssembyVersions.Contains(shortName)) // compare against list of assemblies we ignore revisions for
{
// check if this assembly is already loaded under a different version #
Assembly[] allAss = AppDomain.CurrentDomain.GetAssemblies();
List<Assembly> list = new List<Assembly>(allAss);
var loadedAssembly = list.Find(ass => new AssemblyName(ass.FullName).Name == shortName); // check if we have any version loaded yet
if (loadedAssembly != null)
return loadedAssembly;
else // assembly has not yet been loaded in this domain
{ // probe for assembly by name
Assembly probedAssembly = Assembly.LoadFrom(string.Format("{0}.dll", shortName)); // probe for any match on assembly.dll
return probedAssembly;
}
}
return null; // ignore binding failure -> pass up the stack
};
处理AssemblyResolve
事件的另一种方法是使用自定义bindingRedirect
策略。但是 - 这仅在您知道/bin
应用程序域中存在或当前加载的版本时才有效。
构建时指令
如果您想控制在构建时使用哪个程序集版本,您可以使用Specific Version='true'
添加的程序集引用。