Reputation: 906
In my .NET Core C# App (not ASP) I build a class to handle my services. You have to configure it like this:
MyBaseClass.BuildServiceProvider(serviceCollection =>
serviceCollection
.AddMyConfiguration(out var config)
.AddMyEMailService()
.AddMyLoggingService(config));
The problem is AddMyLoggingService
, because I don't know how to get other services inside. I already passed in the config, what I think is not what DI wants and now I would also have to pass in the E-Mail service.
The logging service looks like this:
public static class ServiceCollectionHelper
{
public static IServiceCollection AddMyLoggingService(this IServiceCollection coll, IConfiguration config)
{
coll.AddLogging(builder =>
builder
.AddConfiguration(config)
.AddDebug()
.AddEventLog()
.AddProvider(new MyTicketLoggerProvider(config))
);
return coll;
}
}
And now MyTicketLoggerProvider
would need the email service that is injected with .AddMyEMailService
to create a ticket (by sending an email to the ticket system).
I have no idea what is the best practice for that.
[EDIT] A workaround is that I create a temporary provider inside AddMyLoggingService
var tmpProvider = coll.BuildServiceProvider();
to be able to access the services.
Upvotes: 6
Views: 1420