barteloma
barteloma

Reputation: 6875

Why Assembly load error occured on IIS publish

I have created an extension method to find my interface implementations in my asp.net core web api project.

    public static List<Type> FromAssembliesMatching<TType>(this AppDomain currentDomain, string searchPattern)
    {
        var referencedPaths = Directory.GetFiles(currentDomain.BaseDirectory, "*.dll").ToList();

        var assemblies = referencedPaths.Select(path => currentDomain.Load(AssemblyName.GetAssemblyName(path)));

        var types = assemblies.SelectMany(s => s.GetTypes().Where(t =>
                typeof(TType).IsAssignableFrom(t)
                && !t.IsInterface
                && !t.IsAbstract))
            .ToList();

        return types;
    }

For example, IMyInterface implemented types are found. This works while developing application.

But when I published it on iis.

System.BadImageFormatException: Could not load file or assembly 'C:\publish\api-ms-win-core-console-l1-1-0.dll'.

The extension method tring to load all dlls. I think c# generated dlls cause errors. How can I solve this problem?

Upvotes: 2

Views: 175

Answers (1)

Lex Li
Lex Li

Reputation: 63234

That's expected.

Due to the deployment approach you use (self-contained), dotnet publish not only copies all your managed assemblies, but also native dependencies, like api-ms-win-core-console-l1-1-0.dll. Those native dependencies cannot be loaded into app domain via reflection, so the exception is perfectly normal.

You have several options to resolve it though,

  • Catch the exception and ignore it.
  • Or proactively check if the dll is native or managed by using PEFile class and related.

Upvotes: 1

Related Questions