question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

NSwag.MSBuild fails under NetCore_31: System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'Startup'

See original GitHub issue

I get the following error using NSwag.MSBuild to generate clients. The project should have been set up to

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate '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.<UseStartup>b__1(IServiceProvider sp)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
...

The .csproj has this set

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
  </PropertyGroup>

  <Target Name="NSwag" AfterTargets="Build">
    <Copy SourceFiles="@(ReferencePath)" DestinationFolder="$(OutDir)References" />
    <Exec Command="$(NSwagExe_Core31) run nswag.json /variables:FilePath=&quot;$(OutDir)$(AssemblyName).dll&quot;" />
    <RemoveDir Directories="$(OutDir)References" />
  </Target>
</Project>

nswag.json looks like so:

{
    "runtime": "NetCore31",
    "defaultVariables": null,
    "documentGenerator": {
        "aspNetCoreToOpenApi": {
            "project": null,
            "msBuildProjectExtensionsPath": null,
            "configuration": null,
            "runtime": null,
            "targetFramework": null,
            "noBuild": false,
            "verbose": true,
            "workingDirectory": null,
            "requireParametersWithoutDefault": true,
            "apiGroupNames": null,
            "defaultPropertyNameHandling": "Default",
            "defaultReferenceTypeNullHandling": "NotNull",
            "defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
            "defaultResponseReferenceTypeNullHandling": "NotNull",
            "defaultEnumHandling": "Integer",
            "flattenInheritanceHierarchy": false,
            "generateKnownTypes": true,
            "generateEnumMappingDescription": false,
            "generateXmlObjects": false,
            "generateAbstractProperties": false,
            "generateAbstractSchemas": true,
            "ignoreObsoleteProperties": false,
            "allowReferencesWithProperties": false,
            "excludedTypeNames": [],
            "serviceHost": null,
            "serviceBasePath": null,
            "serviceSchemes": [],
            "infoTitle": "My Title",
            "infoDescription": null,
            "infoVersion": "1.0.0",
            "documentTemplate": null,
            "documentProcessorTypes": [],
            "operationProcessorTypes": [],
            "typeNameGeneratorType": null,
            "schemaNameGeneratorType": null,
            "contractResolverType": null,
            "serializerSettingsType": null,
            "useDocumentProvider": true,
            "documentName": "v1",
            "aspNetCoreEnvironment": null,
            "createWebHostBuilderMethod": null,
            "startupType": null,
            "allowNullableBodyParameters": true,
            "output": "swagger.json",
            "outputType": "Swagger2",
            "assemblyPaths": [
                "$(FilePath)"
            ],
            "assemblyConfig": null,
            "referencePaths": [],
            "useNuGetCache": false
        }
    },
    "codeGenerators": {
        "openApiToTypeScriptClient": {
            "className": "{controller}Client",
            "moduleName": "",
            "namespace": "",
            "typeScriptVersion": 2.7,
            "template": "Axios",
            "promiseType": "Promise",
            "httpClass": "HttpClient",
            "withCredentials": false,
            "useSingletonProvider": false,
            "injectionTokenType": "OpaqueToken",
            "rxJsVersion": 6.0,
            "dateTimeType": "Date",
            "nullValue": "Undefined",
            "generateClientClasses": true,
            "generateClientInterfaces": false,
            "generateOptionalParameters": false,
            "exportTypes": true,
            "wrapDtoExceptions": false,
            "exceptionClass": "ApiException",
            "clientBaseClass": null,
            "wrapResponses": false,
            "wrapResponseMethods": [],
            "generateResponseClasses": true,
            "responseClass": "SwaggerResponse",
            "protectedMethods": [],
            "configurationClass": null,
            "useTransformOptionsMethod": false,
            "useTransformResultMethod": false,
            "generateDtoTypes": true,
            "operationGenerationMode": "MultipleClientsFromOperationId",
            "markOptionalProperties": true,
            "generateCloneMethod": false,
            "typeStyle": "Class",
            "classTypes": [],
            "extendedClasses": [],
            "extensionCode": null,
            "generateDefaultValues": true,
            "excludedTypeNames": [],
            "excludedParameterNames": [],
            "handleReferences": false,
            "generateConstructorInterface": true,
            "convertConstructorInterfaceData": false,
            "importRequiredTypes": true,
            "useGetBaseUrlMethod": false,
            "baseUrlTokenName": "API_BASE_URL",
            "queryNullValue": "",
            "inlineNamedDictionaries": false,
            "inlineNamedAny": false,
            "templateDirectory": null,
            "typeNameGeneratorType": null,
            "propertyNameGeneratorType": null,
            "enumNameGeneratorType": null,
            "serviceHost": null,
            "serviceSchemes": null,
            "output": "../@company/product-api/ApiClient.generated.ts"
        }
    }
}

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
RicoSutercommented, Jan 20, 2020

Have you tried using “project” parameter (with path to .csproj) and “noBuild”: true instead of “assemblyPaths”? This is the preferred and more tested way to load the project from CLI.

0reactions
shivanarucommented, Mar 30, 2020

Thank you for your reply - @RicoSuter . I figured out the issue was the csproj file had <platform>x64 </platform>. Once I removed it and saved the csproj file, Lamar worked fine and then NSwag had no issue. It worked with either AddOpenApiDocument or AddSwaggerDocument. Either one was fine. The swagger output was different based on which option. I went to OpenApi spec and that was what I needed. So switched to that. NSwag is fantastic!! Thank you again for all your work on it!

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - Unable to resolve service for type 'Microsoft.Extensions ...
Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfigurationRoot' while attempting to activate 'TheWorld.Startup'.
Read more >
Unable to resolve service for type in .NET 5 with entity ...
Hi I am trying to do a website using .NET 5 with some entity framework 3.1.21. I get this error on my Comments/index...
Read more >
NSwag error - System.InvalidOperationException
NSwag error - System.InvalidOperationException: No service for type 'Microsoft.Extensions.DependencyInjection.IServiceProviderFactory`1[Autofac.
Read more >
Unable to resolve service for type Microsoft Extensions ...
Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'Microsoft.FeatureManagement.
Read more >
No service for type 'Microsoft.Extensions.Configuration ...
Coding example for the question "InvalidOperationException: No service for type 'Microsoft.Extensions.Configuration.IConfiguration' has been registered.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found