.Net 6 how to register ILogger into IServiceCollection with implementation

Uday Mahajan 1 Reputation point
2022-09-28T06:26:06.617+00:00

Hi
I am working on a .Net to .Net 6 migration application and want to register ILogger in IService Collection with implementation.
In the existing .Net application, the ILogger is resolved as follows using structure map

ForRequestedType<ILogger>().AsSingletons().TheDefault.Is.ConstructedBy(() =>
GetLoggerFactory().CreateLogger("InstanceName"));

private ILoggerFactory GetLoggerFactory()
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.AppSettings()
.CreateLogger();
return new LoggerFactory()
.AddSerilog();
}

Now I want to register for ILogger on .Net 6. When I tried to register below, it didn't allow to register.

services.AddTransient<ILogger,GetLoggerFactory().CreateLogger("InstanceName")>();

It gave me an error as 'ILogger' is a type,which is not valid in the given context.

So, anyone could you please help us to register for ILogger ?

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Other
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,766 Reputation points Volunteer Moderator
    2022-09-28T20:03:28.02+00:00

    why services.AddTransient? it seems like a singleton. try:

    builder.Services.AddSingleton<ILogger>(GetLoggerFactory().CreateLogger("InstanceName"));

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.