摩尔和绑定重定向

时间:2011-06-27 22:09:23

标签: moles pex-and-moles

我的场景很常见,一个nuget包正在使用V1.0而另一个正在使用V1.1,所以我不得不添加一个绑定重定向。但是,moles runner似乎忽略了App.config和程序集配置文件中的绑定重定向。

要加载App.config,我使用的代码为:How To Read UnitTest Project's App.Config From Test With HostType("Moles")

有什么想法吗?

好的花了我一些时间,但我已经想出如何模仿Binding Redirect的行为。这是我为此所做的代码。将此保留为Wiki,以允许其他人改进此代码:

<!-- 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()).Root;
        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);
        };
    }

0 个答案:

没有答案