Nswag: Automapper crash nswag generator for project

Created on 16 Jan 2019  路  13Comments  路  Source: RicoSuter/NSwag

AutoMapper crash nswag c# client generation when project reference used

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper();
}

with config

    "aspNetCoreToSwagger": {
      "project": "MyServer.csproj",

provide exception

Executing file 'nswag.json'...
  Launcher directory: C:\Users\Efremov\.nuget\packages\nswag.msbuild\12.0.11\tools\NetCore22
  System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
  Could not load file or assembly 'NSwag.CodeGeneration, Version=12.0.11.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
  Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=12.0.11.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
  Could not load file or assembly 'NSwag.CodeGeneration, Version=12.0.11.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
  Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=12.0.11.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
  Could not load file or assembly 'NSwag.CodeGeneration.TypeScript, Version=12.0.11.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
     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 C:\projects\automapper-extensions-microsoft-dependencyinjectio\src\AutoMapper.Extensi
ons.Microsoft.DependencyInjection\ServiceCollectionExtensions.cs:line 72
     at Crypterium.Api.Kyc.Server.Startup.ConfigureServices(IServiceCollection services) in D:\Sources\crypterium.api.kyc\Crypterium.Api.Kyc.Server\Startup.cs:line 37
  --- 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 NSwag.Commands.SwaggerGeneration.AspNetCore.AspNetCoreToSwaggerGeneratorCommandEntryPoint.GetWebHost(String applicationName) in C:\projects\nswag\src\NSwag.Commands\Commands\SwaggerGeneration\AspNetCore\AspNetCoreToSwaggerGeneratorC
ommandEntryPoint.cs:line 64
     at NSwag.Commands.SwaggerGeneration.AspNetCore.AspNetCoreToSwaggerGeneratorCommandEntryPoint.Process(String commandContent, String outputFile, String applicationName) in C:\projects\nswag\src\NSwag.Commands\Commands\SwaggerGeneration\A
spNetCore\AspNetCoreToSwaggerGeneratorCommandEntryPoint.cs:line 26
     --- End of inner exception stack trace ---
     at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
     at NSwag.AspNetCore.Launcher.Program.Main(String[] args) in C:\projects\nswag\src\NSwag.AspNetCore.Launcher\Program.cs:line 161
  System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'.
     at NSwag.Commands.SwaggerGeneration.AspNetCore.AspNetCoreToSwaggerCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\SwaggerGeneration\AspNetCore\AspNetCoreToSwaggerComm
and.cs:line 206
     at NSwag.Commands.NSwagDocumentBase.GenerateSwaggerDocumentAsync() in C:\projects\nswag\src\NSwag.Commands\NSwagDocumentBase.cs:line 268
     at NSwag.Commands.NSwagDocument.ExecuteAsync() in C:\projects\nswag\src\NSwag.Commands\NSwagDocument.cs:line 81
     at NSwag.Commands.Document.ExecuteDocumentCommand.ExecuteDocumentAsync(IConsoleHost host, String filePath) in C:\projects\nswag\src\NSwag.Commands\Commands\Document\ExecuteDocumentCommand.cs:line 77
     at NSwag.Commands.Document.ExecuteDocumentCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Document\ExecuteDocumentCommand.cs:line 36
     at NConsole.CommandLineProcessor.ProcessSingleAsync(String[] args, Object input)
     at NConsole.CommandLineProcessor.ProcessAsync(String[] args, Object input)
     at NConsole.CommandLineProcessor.Process(String[] args, Object input)
     at NSwag.Commands.NSwagCommandProcessor.Process(String[] args) in C:\projects\nswag\src\NSwag.Commands\NSwagCommandProcessor.cs:line 54
NSwag.AssemblyLoader

Most helpful comment

Found solution. Problem is on AutoMapper side. If you just use .AddAutoMapper() it will load and try to resolve all types in all assemblies in your project. If you give him exact assembly (or list of assemblies) to scan it wont touch Nswag and cause a problem. I have my Automapper profiles in same project assembly so for me services.AddAutoMapper(Assembly.GetEntryAssembly()); solves everything.

All 13 comments

Hello,
I have the same issue.
It appears only when I add the line :

services.AddAutoMapper();

Hello,
Can you show us your nswag.json?

please, here is my nswag.json

{
  "runtime": "default",
  "defaultVariables": "",
  "swaggerGenerator": {
    "fromSwagger": {
      "url": "swagger.json"
    }
  },
  "codeGenerators": {
    "swaggerToCSharpClient": {
      "namespace": "MyNamespace",
      "className": "Client",
      "clientBaseClass": "ClientBase",
      "configurationClass": "Configuration",
      "exceptionClass": "ApiClientException",
      "exposeBaseUrl": false,
      "generateClientClasses": true,
      "generateClientInterfaces": true,
      "generateDefaultValues": true,
      "generateDataAnnotations": false,
      "generateDtoTypes": false,
      "generateSyncMethods": false,
      "generateBaseUrlProperty": true,
      "generateJsonMethods": false,
      "generateExceptionClasses": true,
      "useBaseUrl": false,
      "injectHttpClient": true,
      "disposeHttpClient": false,
      "operationGenerationMode": "SingleClientFromOperationId",
      "additionalNamespaceUsages": [
        "System.Collections.Generic",
        "System.Net.Http"
      ],
      "httpClientType": "HttpClient",
      "arrayType": "IList",
      "arrayInstanceType": "List",
      "arrayBaseType": "List",
      "output": "Client.generated.cs"
    }
  }
}

Hi,

You generate CSharp Client from swagger.json. I don't think there has problems.

But we talk about server crash, not client.

Install the client packages, clean your solution, and try again:

Install-Package NSwag.CodeGeneration
Install-Package NSwag.CodeGeneration.CSharp
Install-Package NSwag.CodeGeneration.TypeScript

Why does your web app reference any NSwag.CodeGeneration.* packages?

Got same problem as @LeonidEfremov.
After adding services.AddAutoMapper() in startup for some reason NSwagStudio and NSwag.MSBuild lose ability to generate client. Adding packages mentioned by @davidyee solves problem but these are unnecessary dll in terms of my solution (they are not needed until I run AddAutoMapper().

Found solution. Problem is on AutoMapper side. If you just use .AddAutoMapper() it will load and try to resolve all types in all assemblies in your project. If you give him exact assembly (or list of assemblies) to scan it wont touch Nswag and cause a problem. I have my Automapper profiles in same project assembly so for me services.AddAutoMapper(Assembly.GetEntryAssembly()); solves everything.

I faced the same problem and the solution was to create a MapperConfiguration instead of using the AddAutoMapper:

var configuration = new MapperConfiguration(cfg =>
{
       cfg.AddProfile(new CustomProfile());
});

services.AddSingleton(x => configuration.CreateMapper());

The IMapper can be used then in the constructor with no problem.

I think this issue can be closed, because the method services.AddAutoMapper(); without parameter no longer exists.
You always have to pass the assemblies AutoMapper needs to scan, see https://docs.automapper.org/en/latest/Dependency-injection.html?highlight=AddAutoMapper#asp-net-core.

I currently have this issue even though I've changed the way I'm injecting the AutoMapper, but I didn't have this issue before at some point. I'm currently working to figure out what I changed that causes this error to occur.

Ahh it appears I missed the instruction to add this to my csproj:
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>

Was this page helpful?
0 / 5 - 0 ratings