Unable to resolve service for type 'System.String' while attempting to activate 'MyService'

spottedmahn picture spottedmahn · Apr 13, 2018 · Viewed 18.2k times · Source

I'm seeing the following exception in my Service Fabric Stateless ASP.NET Core app.

System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate 'MyService'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.CreateCallSite(ServiceProvider provider, ISet`1 callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetResolveCallSite(IService service, ISet`1 callSiteChain)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetServiceCallSite(Type serviceType, ISet`1 callSiteChain)

How can it not be able to resolve System.String? How do I debug this further?

Answer

Nkosi picture Nkosi · Apr 14, 2018

The default DI framework in Asp.Net Core is limited in what features are available. Assuming a class constructor like

public MyService(string dependencyString) {
    //...
}

There is no way for the container to know what value to use for the dependent string to be injected into the service.

In the above case the missing string can be provided using one of the overloads when adding the service to the collection.

//...

services.AddScoped<IMyService>(_ => new MyService("value here"));

//...

That way when the service is being activated it can be properly returned.


Documentation Reference: Dependency injection in ASP.NET Core -> Constructor injection behavior (v2.1)