I'm currently working on a project, where I have a blueprint for how my Worker class is defined, the Worker class is located in a SharedLibraryModel in a different solution folder.
public class Worker : BackgroundService
{
private readonly Controller _controller;
private string ListenQueueName;
public Worker(Controller controller, string listenQueueName)
{
_controller = controller;
ListenQueueName = listenQueueName;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
}
I have also made a Controller class and IController interface.
public class Controller : IController
{
public (string, string) MessageReceived(string inMessage)
{
return ('some', 'string')
};
}
I want to use the above definition of a Worker class in my CustomerWorker, which I have defined as
public class CustomerWorker : SharedModelLibrary.Worker
{
public CustomerController _customerController;
public readonly string ListenQueueName = 'customers';
public CustomerWorker(CustomerController _customerController, string ListenQueueName)
: base(_customerController, ListenQueueName)
{
}
The CustomerController inherits from the Controller.
But when the following is called in Program.cs
builder.Services.AddSingleton<ICustomerMessage, CustomerService>();
builder.Services.AddSingleton<CustomerController>();
builder.Services.AddHostedService<CustomerWorker>();
var app = builder.Build();
I get the error message
"Some services are not able to be constructed (Error while validating the service
descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton
ImplementationType: CustomerMicroService.CustomerWorker': Unable to resolve service for type
'System.String' while attempting to activate 'CustomerMicroService.CustomerWorker'.)"
I'm not sure if its improper use of inheritance or something I have misunderstood in regard to the AddHostedService and AddSingleton.
Any help would be much appreciated.
CodePudding user response:
The error message is very clear. Unable to resolve service for type 'System.String'
, It seems you want to inject string ListenQueueName
into CustomerWorker
class. but you have not register string type. I know it is impossible to register string type.
I don't know the ListenQueueName
purpose.
you have two way to solve your issue.
- register
Customerworker
by handle like below:
builder.Services.AddHostedService<CustomerWorker>(sp =>
{
var customerController = sp.GetRequiredService<CustomerController>();
return new CustomerWorker(customerController, "ListenQueueName");
});
- wrapper your
ListenQueueName
into a class and then register that class.