In the bootstrapping logic of my application I was using some reflection to dynamically register dependencies in the IoC container:
public IFrameworkBuilder ScanForModules() | |
{ | |
var currentDomain = new List<Assembly>(); | |
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) | |
{ | |
currentDomain.Add(assembly); | |
} | |
var modules = currentDomain | |
.SelectMany(a => a.ExportedTypes.Where(t => t.IsModule())); | |
_modules.AddRange(modules); | |
return this; | |
} |
When I was using the same code together with the .NET Core Test server the code above didn't work but resulted in the following exception:
Message:
System.NotSupportedException : The invoked member is not supported in a dynamic assembly.
Stack Trace:
InternalAssemblyBuilder.GetExportedTypes()
Assembly.get_ExportedTypes()
<>c.<ScanForModules>b__5_0(Assembly a)
SelectManySingleSelectorIterator`2.MoveNext()
List`1.InsertRange(Int32 index, IEnumerable`1 collection)
FrameworkBuilder.ScanForModules()
<>c__DisplayClass0_0.<UseSOFACore>b__1(HostBuilderContext ctx, ContainerBuilder builder)
ConfigureContainerAdapter`1.ConfigureContainer(HostBuilderContext hostContext, Object containerBuilder)
HostBuilder.CreateServiceProvider()
HostBuilder.Build()
WebApplicationFactory`1.CreateHost(IHostBuilder builder)
WebApplicationFactory`1.EnsureServer()
WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers)
WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers)
WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options)
WebApplicationFactory`1.CreateClient()
ConversionApiTests.ctor(SelfHostedApi fixture) line 19
This is because an Assembly is generated dynamically during the tests and the "GetExportedTypes()" is not supported on these assemblies.
To fix the error I updated the code to remove dynamic assemblies from the iteration:
//Exclude dynamically generated assemblies | |
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(p => !p.IsDynamic)) | |
{ | |
currentDomain.Add(assembly); | |
} |