Nswag: System.InvalidOperationException: The ConfigureServices method must either be parameterless or take only one parameter

Created on 25 Jan 2019  路  17Comments  路  Source: RicoSuter/NSwag

Have an ASP.NET CORE 2.1 project.
I have already read https://github.com/RSuter/NSwag/wiki/Assembly-loading and added this to my project:

  <PropertyGroup>
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
  </PropertyGroup>

After trying to execute the command:

12.0.12\tools\Win>nswag.exe aspnetcore2swagger /assembly:F:\Test\MyProject.dll /runtime:Net
Core21 /output:swagger.json

First time got an error:
System.IO.FileLoadException: Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies.

It has been fixed by installation package System.Diagnostics.DiagnosticSource (newer version than 4.0.3.0).

After that an error occurred:
system.invalidoperationexception: unable to resolve service for type 'microsoft.extensions.configuration.iconfiguration' while attempting to activate Startup.

This is a very strange. But I tried to install the package Microsoft.Extensions.DependencyInjection explicitly and it fixed it.

The next error is:
System.InvalidOperationException: The ConfigureServices method must either be parameterless or take only one parameter of type IServiceCollection.
And I don't know what to do with this. My ConfigureServices has only one param: public void ConfigureServices(IServiceCollection services).

I spent a lot of time, tried to create a new Core 2.1 project from VS2017 template and got the same errors.

question

Most helpful comment

Thank you @paillave. At the end I made it work by tweaking "/project:pathto.csproj /noBuild:true" approach

All 17 comments

Seems like an assembly loading/binder problem, have you checked this page? https://github.com/RSuter/NSwag/wiki/Assembly-loading#net-core

Hi,

I have the same problem. The error showed up after I upgraded nuget packages from 3.1.0 to 3.1.1, before the upgrade it was running smoothly.

I have already tried all things mentioned in the link above: https://github.com/RSuter/NSwag/wiki/Assembly-loading#net-core

Have you tried to update nswag?

Yes.

NSwag.AspNetCore: 13.2.3
NSwag.MSBuild: 13.2.3

I'm having the same error:
Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration'

I'm using the command aspnetcore2openapi with NetCore31

This also started happening when I did nuget updates, everything was fine before.

I'm using:
<Exec Command="$(NSwagExe_Core31) aspnetcore2openapi /assembly:$(TargetDir)$(AssemblyName).dll /output:wwwroot/api-docs/swagger.json" />

This is the exact error I"m getting:

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'ScatterlingLocationWeb.Startup'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
at Microsoft.AspNetCore.Hosting.StartupLoader.LoadMethods(IServiceProvider hostingServiceProvider, Type startupType, String environmentName)

at Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions.<>c__DisplayClass3_0.b__1(IServiceProvider sp)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetServiceT
at Microsoft.AspNetCore.Hosting.WebHost.EnsureStartup()
at Microsoft.AspNetCore.Hosting.WebHost.EnsureApplicationServices()
at Microsoft.AspNetCore.Hosting.WebHost.Initialize()
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at NSwag.Commands.Generation.OpenApiGeneratorCommandBase1.CreateWebHostAsync(AssemblyLoader assemblyLoader) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\OpenApiGeneratorCommandBase.cs:line 342 at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.RunIsolatedAsync(AssemblyLoader assemblyLoader) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 310 at NSwag.Commands.IsolatedCommandBase1.IsolatedCommandAssemblyLoader1.Run(String commandType, String commandData, String[] assemblyPaths, String[] referencePaths) in C:\projects\nswag\src\NSwag.Commands\Commands\IsolatedCommandBase.cs:line 76 at NSwag.Commands.IsolatedCommandBase1.<>c__DisplayClass17_0.b__0() in C:\projects\nswag\src\NSwag.Commands\Commands\IsolatedCommandBase.cs:line 61
at System.Threading.Tasks.Task1.InnerInvoke() at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj) at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location where exception was thrown --- at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread) --- End of stack trace from previous location where exception was thrown --- at NSwag.Commands.IsolatedCommandBase1.RunIsolatedAsync(String configurationFile) in C:\projects\nswag\src\NSwag.Commands\Commands\IsolatedCommandBase.cs:line 61
at NSwag.Commands.IsolatedSwaggerOutputCommandBase`1.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\IsolatedSwaggerOutputCommandBase.cs:line 47
at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 95
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 56

Instead of /assembly

Thanks for the quick reply. I've tried using the project instead of the assembly and I get a different set of errors. Also note that this all worked until I updated some nuget packages today.

Here is the new error:

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.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration.TypeScript, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.CodeGeneration.TypeScript, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
Could not load file or assembly 'NSwag.Generation.WebApi, Version=13.2.3.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 AutoMapper.ServiceCollectionExtensions.<>c.b__11_2(Assembly a)
at System.Linq.Enumerable.SelectManySingleSelectorIterator2.ToArray() at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)
at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action2 configAction, IEnumerable1 assembliesToScan, ServiceLifetime serviceLifetime)
at AutoMapper.ServiceCollectionExtensions.AddAutoMapper(IServiceCollection services, Assembly[] assemblies)
at Startup.ConfigureServices(IServiceCollection services) in Startup.cs:line 144
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 Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.g__Startup|0(IServiceCollection serviceCollection)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.b__0(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.GetServiceProvider(String applicationName) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 80
at NSwag.Commands.Generation.AspNetCore.AspNetCoreToOpenApiGeneratorCommandEntryPoint.Process(String commandContent, String outputFile, String applicationName) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiGeneratorCommandEntryPoint.cs:line 26
System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration.CSharp, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration.TypeScript, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration.TypeScript, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.CodeGeneration.TypeScript, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.CodeGeneration.TypeScript, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

System.IO.FileNotFoundException: Could not load file or assembly 'NSwag.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'. The system cannot find the file specified.
File name: 'NSwag.Generation.WebApi, Version=13.2.3.0, Culture=neutral, PublicKeyToken=c2d88086e098d109'

--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
Done executing command. Exit Code: 1.
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) System.InvalidOperationException: Swagger generation failed with non-zero exit code '1'.
at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 221
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 56

For me this helped:

Use /project:pathto.csproj /noBuild:true

I manually added all the Nswag library listed in the error I posted and it works. Thanks.

the /project:pathto.csproj /noBuild:true options gives me this:

System.InvalidOperationException: Process dotnet timed out.
at NSwag.Commands.Generation.AspNetCore.Exe.RunAsync(String executable, IReadOnlyList1 args, IConsoleHost console, Nullable1 timeout) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\Exe.cs:line 70
at NSwag.Commands.Generation.AspNetCore.ProjectMetadata.GetProjectMetadata(String file, String buildExtensionsDir, String framework, String configuration, String runtime, Boolean noBuild, IConsoleHost console) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\ProjectMetadata.cs:line 143
at NSwag.Commands.Generation.AspNetCore.AspNetCoreToSwaggerCommand.RunAsync(CommandLineProcessor processor, IConsoleHost host) in C:\projects\nswag\src\NSwag.Commands\Commands\Generation\AspNetCore\AspNetCoreToOpenApiCommand.cs:line 103
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 56

Hello,
I have exactly the same problem as mentioned in first post. No suggenstion in this thread helped me. I use these NSwag packages:

 <PackageReference Include="NSwag.AspNetCore" Version="13.4.2" />
 <PackageReference Include="NSwag.MSBuild" Version="13.4.2" />

and this is my build step:

<Target Name="GenerateSpecification" BeforeTargets="AfterBuild">
    <PropertyGroup>
      <Artifact>$(CXPMainSrcPath)\Services\output\Specification.json"</Artifact>
    </PropertyGroup>
    <Copy SourceFiles="@(Reference)" DestinationFolder="$(OutDir)References" />
    <Exec EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="$(NSwagExe_Core31) aspnetcore2openapi /runtime:NetCore22 /assembly:$(TargetDir)$(AssemblyName).dll /output:$(Artifact)" />
    <RemoveDir Directories="$(OutDir)References" />
  </Target>

I am targeting .NET Core 3.1 but ASP.NET Core 2.2 is referenced. Any new suggestions how to trace down this binding issue?

At the end of the day, I ended up doing this:

  • Tweak my application to accept a parameter that corresponds to the output path to the swagger file.

    • If this parameter is transmitted, I don't run the webapp but I generate the file using the core of nswag after extracting webapi dictionary against the webHost

    • If this parameter is not transmitted, I start the webHost normally

  • Tweak the csproj to execute the command line using the freshly compiled dll at the end of the build (so before the publish that runs npm install and npm build) for it to issue the precious file during the compilation!
  • My typescript proxy is generated by an npm task thanks to node-ts. I also run this generation in my npm prebuild event.

The very big quality of this solution is that it doesn't rely on loading the application from an external assembly (the nswag exe) that actually relies on some specific versions of dependencies and causes failures. Here, the file is generated by the application it self once it is compiled.

Here is my program.cs

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.CommandLineUtils;
using FundProcess.Pms.DataAccess;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Mvc.ApiExplorer;

namespace My.Application
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var commandLineApplication = new CommandLineApplication(false);
            var generateSwaggerSpecs = commandLineApplication.Option("--swagger | -sw <filePath>", "Generate the swagger specification file", CommandOptionType.SingleValue);
            commandLineApplication.HelpOption("-? | -h | --help");
            commandLineApplication.OnExecute(async () =>
            {
                await ExecuteAppAsync(args, generateSwaggerSpecs);
                return 0;
            });
            commandLineApplication.Execute(args);
        }
        public static async Task ExecuteAppAsync(string[] args, CommandOption generateSwaggerSpecs)
        {
            var webHost = Host
                .CreateDefaultBuilder(args)
                .UseServiceProviderFactory(new AutofacMultitenantServiceProviderFactory(Startup.ConfigureMultitenantContainer))
                .ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.UseStartup<Startup>())
                .Build();
            // if an output file path is transmitted to the application, I produce the file instead of running the webapp
            if (generateSwaggerSpecs.HasValue())
            {
                var apiDescriptionProvider = (IApiDescriptionGroupCollectionProvider)webHost.Services.GetService(typeof(IApiDescriptionGroupCollectionProvider));
                SaveSwagger(apiDescriptionProvider, generateSwaggerSpecs.Value());
            }
            else
                await webHost.RunAsync();
        }
        private static void SaveSwagger(IApiDescriptionGroupCollectionProvider apiDescriptionProvider, string filePath)
        {
            // these are the same parameters than the ones I use 
            // to setup my web api in the Startup class
            var nswagSettings = new NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGeneratorSettings();
            nswagSettings.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
            {
                Converters = new[] { new Newtonsoft.Json.Converters.StringEnumConverter() },
                NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            };
            nswagSettings.DocumentName = "v1";
            nswagSettings.Title = "My Api";
            var v = typeof(Program).Assembly.GetName().Version;
            nswagSettings.Version = $"{v.Major}.{v.Minor}.{v.Revision}";

            // this is where I start to use the actual core of nswag
            var generator = new NSwag.Generation.AspNetCore.AspNetCoreOpenApiDocumentGenerator(nswagSettings);
            var document = generator.GenerateAsync(apiDescriptionProvider.ApiDescriptionGroups).Result.ToJson();
            File.WriteAllText(filePath, document);
        }
    }
}

Here is the little tweak I added in my .csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <Version>1.1.0</Version>
    <SpaRoot>ClientApp\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
    <AssemblyName>My.Application</AssemblyName>
    <RootNamespace>My.Application</RootNamespace>
  </PropertyGroup>
...
  <Target Name="NSwag" AfterTargets="Build">
      <Exec EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="dotnet $(TargetDir)My.Application.dll -sw $(SpaRoot)/swagger.json" />
  </Target>
...

Thank you @paillave. At the end I made it work by tweaking "/project:pathto.csproj /noBuild:true" approach

Was this page helpful?
0 / 5 - 0 ratings