Исключение ReflectionTypeLoadException в Asp.Net Core в памяти TestServer - PullRequest
0 голосов
/ 05 февраля 2019

Я создаю IWebHostBuilder примерно так:

public IWebHostBuilder GetWebHostBuilder()
{
     return new WebHostBuilder().UseContentRoot(_contentRoot)
                                       .ConfigureServices(InitializeServiceCollection)
                                       .UseEnvironment(_environment)
                                       .UseConfiguration(GetConfiguration())
                                       .UseStartup(typeof(TStartup));
}

Здесь InitializeServiceCollection реализован так:

private void InitializeServiceCollection(IServiceCollection services)
{
     var manager = new ApplicationPartManager();

     manager.ApplicationParts.Add(new AssemblyPart(_assembly));
     manager.FeatureProviders.Add(new ControllerFeatureProvider());
     manager.FeatureProviders.Add(new ViewComponentFeatureProvider());

     services.AddSingleton(manager);
}

Затем я создаю TestServer вот так:

var myTestServer = new TestServer(GetWebHostBuilder());

Здесь я получаю исключение (полное исключение ниже).Он вызывается при вызове метода services.AddAutoMapper(); в тестируемой системе.Однако, когда я запускаю тестируемую систему самостоятельно и тестирую ее вручную с помощью Postman, она работает нормально, и сопоставление объектов с Automapper также работает хорошо.Это просто вызывает исключение в интеграционном тесте.

Полное исключение:

System.AggregateException : One or more errors occurred. (Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.) (The following constructor parameters did not have matching fixture data: TestFixture fixture)
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames' from assembly 'Microsoft.EntityFrameworkCore.Relational, Version=2.2.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
---- The following constructor parameters did not have matching fixture data: TestFixture fixture

----- Inner Stack Trace #1 (System.Reflection.ReflectionTypeLoadException) -----
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeAssembly.get_DefinedTypes()
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`2 configAction, IEnumerable`1 assembliesToScan) in xxx\automapper-extensions-microsoft-dependencyinjectio\src\AutoMapper.Extensions.Microsoft.DependencyInjection\ServiceCollectionExtensions.cs:line 72
   at xxx.Startup.ConfigureServices(IServiceCollection services) in xxx\Startup.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
   at xxx.Tests.TestFixture.InitializeServer() in xxx.Tests\TestFixture.cs:line 67
   at xxx.Tests.TestFixture..ctor() in xxx.Tests\TestFixture.cs:line 31
----- Inner Stack Trace #2 (Xunit.Sdk.TestClassException) -----

1 Ответ

0 голосов
/ 05 февраля 2019

Итак, мне удалось решить проблему, заменив services.AddAutoMapper() перегрузкой services.AddAutoMapper(Type[] types).Не уверен, что не так с оригинальным методом, но чтобы избежать этого рефлексивного вызова для сборок, я использовал эту перегрузку, и теперь она работает.

...