Moles and Binding Redirects
The scenario I have is pretty common, one nuget package is using V1.0 and another is using V1.1 so I had to add a Binding Redirect. However, the moles runner appears to be ignoring the binding redirect in both the App.config and assembly config file.
To load the App.config I am using the code found on: How To Read UnitTest Project's App.Config From Test With HostType("Moles")
Any ideas?
Ok took me some time but I have figured out how to mimic the behavior of Binding Redirect. This is the code that I did for that. Leave this as Wiki to allow others to improve upon this code:
<!-- language: lang-cs -->
public static void MoleBindingRedirect()
{
try
{
var fileMap = new ExeConfigurationFileMap();
Assembly assembly = Assembly.GetExecutingAssembly();
fileMap.ExeConfigFilename = assembly.Location + ".config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
ConfigurationSection assemblyBindingSection = config.Sections["runtime"];
var sectionRoot = XDocument.Parse(assemblyBindingSection.SectionInformation.GetRawXml()).Ro开发者_开发技巧ot;
var assemblyBinding = sectionRoot.Elements(XName.Get("assemblyBinding", "urn:schemas-microsoft-com:asm.v1"));
if (assemblyBinding == null)
return;
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var assemblyToLoad = new AssemblyName(args.Name);
var query = from dependency in assemblyBinding.Elements(XName.Get("dependentAssembly", "urn:schemas-microsoft-com:asm.v1"))
from identity in dependency.Elements(XName.Get("assemblyIdentity", "urn:schemas-microsoft-com:asm.v1"))
from attribute in identity.Attributes()
where attribute.Value == assemblyToLoad.Name
select dependency;
if (!query.Any())
return null;
var assemblyDefinition = query.First();
var identityElement = assemblyDefinition.Element(XName.Get("assemblyIdentity", "urn:schemas-microsoft-com:asm.v1"));
var bindingRedirectElement = assemblyDefinition.Element(XName.Get("bindingRedirect", "urn:schemas-microsoft-com:asm.v1"));
var assemblyName = identityElement.Attribute("name").Value;
var assemblyPublicKeyToken = identityElement.Attribute("publicKeyToken");
var assemblyCulture = identityElement.Attribute("culture");
var assemblyVersion = bindingRedirectElement.Attribute("newVersion").Value;
if (assemblyPublicKeyToken != null && !string.IsNullOrWhiteSpace(assemblyPublicKeyToken.Value))
assemblyName += ", PublicKeyToken=" + assemblyPublicKeyToken.Value;
if (assemblyCulture != null && !string.IsNullOrWhiteSpace(assemblyCulture.Value))
assemblyName += ", Culture=" + assemblyCulture.Value;
if (!string.IsNullOrWhiteSpace(assemblyVersion))
assemblyName += ", Version=" + assemblyVersion;
return Assembly.Load(assemblyName);
};
}
精彩评论