53

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?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
spottedmahn
  • 14,823
  • 13
  • 108
  • 178
  • 1
    'MyService' probably expect a string in the constructor and the IoC Container does not know how to resolve it, you will need to review the service registration to configure it to iae the string required – Diego Mendes Apr 13 '18 at 23:33
  • It does. Maybe it is that obvious. Come to think of it, I don’t think I’ve ever taken a dependency on a string before. Only thinks like ILogger, IOptions. @DiegoMendes – spottedmahn Apr 13 '18 at 23:45
  • Duh, it wouldn’t know where to get the string instances from! – spottedmahn Apr 14 '18 at 00:47

3 Answers3

96

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)

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Nkosi
  • 235,767
  • 35
  • 427
  • 472
0

In WPF I had to add to App.xaml.cs the line services.AddScoped

public App()
{
     _appHost = Host.CreateDefaultBuilder()
        .ConfigureServices((hostContext, services) =>   {
            ConfigureServices(services);
        services.AddSingleton<IBlobOnes, BlobOnes>();
        services.AddScoped<IBlobOnes>(g => new BlobOnes(App.stringID, 0));    
    }).Build();
}
0

To anyone looking at this question who has a project with an automated service to add scoped services. Check your query handler to see if you are defining something in the constructor that can't be found like an anon string.

Sean Dillon
  • 140
  • 8