Reputation: 4405
I have the following interface in my .NET Core web application:
public interface IIntegrationManagerService : IHostedService
{
Task<List<IFunciones>> GetFunctionList();
}
The implementation is as follows:
public class IntegrationManagerService : IIntegrationManagerService, IDisposable
I am adding in Program.cs this way:
services.AddHostedService<IIntegrationManagerService>();
When doing that, an exception is thrown when services are built.
If I change the above line with this:
services.AddHostedService<IntegrationManagerService>();
Services are built, but an exception is thrown when the class where the object is to be injected is instantiated.
If I inject IHostedService
no exception is thrown, but I cannot use IIntegrationManagerService
methods.
How can I do it?
I tried by adding a singleton, but Start
method of the service obviously is not called.
Upvotes: 0
Views: 190
Reputation: 73
Are you trying to reference your Hosted Service from a controller? If I recall, Hosted Services are added to the DI Container with scoped lifetime. They can be pulled from the IServiceProvider if you inject it into your controller:
var scope = serviceProvider.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IIntegrationManagerService>();
If this doesn't work, you can configure your hosted service to be responsive to events raised within the controller. This might be considered an anti-pattern, but would provide a viable, reusable solution.
Good luck!
Upvotes: 0