且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

自动映射器随机错误

更新时间:2022-05-29 23:14:19

好,我终于明白了.

AppDomain.CurrentDomain.GetAssemblies()

我的代码有时有时无法获取我的映射程序集,因此在丢失时会出现错误.通过强制应用程序查找所有程序集来替换此代码,从而解决了我的问题.

piece of my code sometimes does not get my mapping assembly so while it is missing I get an error. Replacing this code by forcing the app to find all assemblies solved my problem.

感谢您的答复.

Andrew Brown 询问解决方案的代码时,我意识到我还没有包含源代码片段.这是AssemblyLocator:

As Andrew Brown asked about the code of the solution, I realized that I have not included the source code snippet. Here is the AssemblyLocator:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Compilation;

public static class AssemblyLocator
{
    private static readonly ReadOnlyCollection<Assembly> AllAssemblies;
    private static readonly ReadOnlyCollection<Assembly> BinAssemblies;

    static AssemblyLocator()
    {
        AllAssemblies = new ReadOnlyCollection<Assembly>(
            BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList());

        IList<Assembly> binAssemblies = new List<Assembly>();

        string binFolder = HttpRuntime.AppDomainAppPath + "bin\\";
        IList<string> dllFiles = Directory.GetFiles(binFolder, "*.dll",
            SearchOption.TopDirectoryOnly).ToList();

        foreach (string dllFile in dllFiles)
        {
            AssemblyName assemblyName = AssemblyName.GetAssemblyName(dllFile);

            Assembly locatedAssembly = AllAssemblies.FirstOrDefault(a =>
                AssemblyName.ReferenceMatchesDefinition(
                    a.GetName(), assemblyName));

            if (locatedAssembly != null)
            {
                binAssemblies.Add(locatedAssembly);
            }
        }

        BinAssemblies = new ReadOnlyCollection<Assembly>(binAssemblies);
    }

    public static ReadOnlyCollection<Assembly> GetAssemblies()
    {
        return AllAssemblies;
    }

    public static ReadOnlyCollection<Assembly> GetBinFolderAssemblies()
    {
        return BinAssemblies;
    }
}

因此,我不是使用AppDomain.CurrentDomain.GetAssemblies(),而是调用提供的帮助程序类的GetAssemblies()方法,例如:

Hence, instead of using AppDomain.CurrentDomain.GetAssemblies(), I am calling the GetAssemblies() method of the provided helper class like:

//Scan all assemblies to find an Auto Mapper Profile
//var profiles = AppDomain.CurrentDomain.GetAssemblies()
//                        .SelectMany(a => a.GetTypes())
//                        .Where(t => t.BaseType == typeof(Profile));
var profiles = AssemblyLocator.GetAssemblies().
                               SelectMany(a => a.GetTypes()).
                               Where(t => t.BaseType == typeof(Profile));