跨程序集反射问题:IsAssignableFrom无法识别ICosmosJob实现
问题:跨程序集下IsAssignableFrom无法识别接口继承关系
我正尝试让Test1测试用例正常运行。经排查,问题源于ICosmosJob与ICosmosApi_Shipment_Workorder位于不同程序集——将两者放在同一程序集时测试可正常执行。目前无法让typeof(ICosmosJob).IsAssignableFrom(t)返回true,求解决思路。
相关代码
[Test] public void Test1() { ServiceSettingsInfo.ApiConnectionString = "https://testcosmoscoreapi.bergerwebservices.com/"; ServiceSettingsInfo.ServiceId = 1138; string assemblyPath = @"C:\Websites\CosmosJobProcessor\CosmosJobAssemblies\CosmosApi_Shipment_Workorder"; ICosmosJob implementation = null; bool isimplemented = false; foreach (string assemblyFile in Directory.GetFiles(assemblyPath, "CosmosApi_Shipment_Workorder.dll")) { Assembly assembly = Assembly.LoadFrom(assemblyFile); var types = assembly.GetExportedTypes().Where(t => typeof(ICosmosJob).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract); // this works var types = assembly.GetExportedTypes().Where(t => typeof(ICosmosApi_Shipment_Workorder).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract); foreach (var type in types) { if (type.Name == "CosmosApi_Shipment_Workorder") { implementation = (ICosmosJob)Activator.CreateInstance(type); implementation.ExecuteAsync(new CosmosJobEntityDto(), "", CancellationToken.None).Wait(); isimplemented = true; break; } } } Assert.That(isimplemented, Is.True); } public interface ICosmosJob { Task<CosmosJobResponse> ExecuteAsync(CosmosJobEntityDto cosmosJobEntityDto, string url, CancellationToken stoppingToken); } public interface ICosmosApi_Shipment_Workorder: ICosmosJob { ... }
解决思路
排查程序集重复加载:测试项目和目标dll可能加载了两份
ICosmosJob定义。因为Assembly.LoadFrom会加载指定路径的dll,若测试项目本身引用了包含ICosmosJob的程序集,会导致同一接口存在于不同程序集实例中,类型匹配失败。
处理方式:改用Assembly.Load加载程序集强名称,或确保测试项目与目标dll引用的ICosmosJob程序集版本完全一致,避免重复加载。验证类型继承链:在代码中输出目标类型的接口列表,确认
ICosmosApi_Shipment_Workorder继承的ICosmosJob是否与测试项目中的为同一实例:foreach (var iface in type.GetInterfaces()) { Console.WriteLine($"{type.Name} 实现了 {iface.FullName},来自程序集 {iface.Assembly.FullName}"); }若输出的程序集信息与测试项目中的
ICosmosJob不一致,即可确认是重复加载问题。通过全名匹配替代IsAssignableFrom:如果强名称加载有障碍,可以通过类型完整名称(含命名空间)来筛选:
var targetIfaceFullName = typeof(ICosmosJob).FullName; var types = assembly.GetExportedTypes() .Where(t => !t.IsInterface && !t.IsAbstract && t.GetInterfaces().Any(i => i.FullName == targetIfaceFullName));添加程序集绑定重定向:若因版本不一致导致加载问题,可在测试项目的
app.config中添加绑定重定向,确保所有引用指向同一版本的ICosmosJob程序集:<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="YourICosmosJobAssembly" publicKeyToken="公钥令牌" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-当前版本" newVersion="当前版本" /> </dependentAssembly> </assemblyBinding> </runtime>
内容的提问来源于stack exchange,提问作者user1337493
相关产品推荐
相关产品推荐

