Is it possible to add all IHostedService
implemented classes in a loop without adding them individually in ASP.NET Core 6?
Let's say we have this two implementations:
public class FirstImplementationOfHostedService : IHostedService
{
// ...
}
public class SecondImplementationOfHostedService : IHostedService
{
// ...
}
The default way in Program.cs
to add them is:
builder.Services.AddHostedService<FirstImplementationOfHostedService>();
builder.Services.AddHostedService<SecondImplementationOfHostedService>();
But, what about having a hundred implementations?
There has to be a better way to add (at runtime) the one hundred implementations in Program.cs
without explicitly spelling out all their names!
You can use an nuget package like this or you can create an extension method and get all references of services with reflection:
and than call it at startup.cs
But be careful , you are registering services in a collection. There is a long version of answer here. You should check.