简体   繁体   中英

C# library which references older version of nuget dependency causes assembly reflection to fail

One of the nuget dependencies in my project ( Swashbuckle ) requires a version of the System.Web.Http library (4.0.0.0) that is older than the version required by the rest of the project (5.2.3.0).

Swashbuckle requires that I write a class implementing a certain interface:

public class OperationFilter : Swashbuckle.Swagger.IOperationFilter
{
    public void Apply(Swashbuckle.Swagger.Operation operation, Swashbuckle.Swagger.SchemaRegistry schemaRegistry, System.Web.Http.Description.ApiDescription apiDescription)
    {

    }
}

The important part above is the apiDescription parameter of Apply .

When building the project normally, the above compiles and runs fine. However, when I reflect over the running assembly using assembly.GetTypes() ,

var asm = System.Reflection.Assembly.GetExecutingAssembly();
var types = asm.GetTypes()

a ReflectionTypeLoadException is thrown, with the following loader exception details:

Method 'Apply' in type 'OperationFilter' from assembly 'MyAssembly, 
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an 
implementation.

this question references the above exception, but none of the solutions posed seem to work. I tried to solve the issue by adding a bindingRedirect to Web.config:

        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
        </dependentAssembly>

However, that didn't seem to do anything.

How can I get this type to load properly?

EDIT: I've created a minimal reproduction of the issue . A build task in BuildTask.targets loads the project assembly and then tries to load all the types. The errors are thrown and displayed.

Following up on my comments...

I just tested the sample project and this issue can be fixed by using Swagger-Net .

That is my fork of Swashbuckle, I've upgraded all dependencies to the latest and using also latest of the Swagger-UI (3.x), it is quite a drastic change from the old one, let me know how you like it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM