Skip to main content

How to Get an ILogger in a Class with Constructor Injection in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

A class that does real work should be able to log what it does. In .NET, it doesn't create a logger itself: it asks for an ILogger<T> in its constructor, and dependency injection passes one in, already set up with the app's logging.

Syntax​

Syntax
class <ClassName>
{
private readonly ILogger<<ClassName>> _logger;

public <ClassName>(ILogger<<ClassName>> logger)
{
_logger = logger;
}
}
PartWhat it does
ILogger<<ClassName>>A logger whose category is the class's name, so every line it writes says where it came from
The constructor parameterTells dependency injection that the class needs a logger. You don't pass it yourself
_logger = logger;Keeps it in a readonly field for the class's methods to use

Microsoft's .NET logging overview: "If your application uses Dependency Injection (DI) or a host such as ASP.NET's WebApplication or Generic Host, use ILoggerFactory and ILogger objects from the DI container rather than creating them directly." And: "The DI container locates an ILogger with the correct category and supplies it as the constructor argument."

The Example​

An OrderService logs a line each time an order is placed. The program uses the .NET generic host, which sets up dependency injection and logging to the console, registers the service, gets it back and places one order.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which adds the Microsoft.Extensions.Hosting package with a # line, creates a host builder, registers OrderService with AddTransient, builds the host, gets OrderService with GetRequiredService and places an order for Tea, with an OrderService class that receives ILogger of OrderService in its constructor and logs Placed an order for the item.

main.cs
#:package Microsoft.Extensions.Hosting@10.0.15
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddTransient<OrderService>();

using IHost host = builder.Build();

OrderService orders = host.Services.GetRequiredService<OrderService>();
orders.Place("Tea");

class OrderService
{
private readonly ILogger<OrderService> _logger;

public OrderService(ILogger<OrderService> logger)
{
_logger = logger;
}

public void Place(string item)
{
_logger.LogInformation("Placed an order for {Item}.", item);
}
}
  1. #:package adds the Microsoft.Extensions.Hosting NuGet package to this one-file program. The first run downloads it.
  2. Host.CreateApplicationBuilder(args) sets up dependency injection and logging, with the console as one of the outputs.
  3. AddTransient<OrderService>() registers the class, so the host knows how to create it.
  4. GetRequiredService<OrderService>() asks for one. The host sees that the constructor needs an ILogger<OrderService> and passes it in.

Step 2: Run It​

Terminal
dotnet run main.cs
Output
info: OrderService[0]
Placed an order for Tea.

A zsh terminal where dotnet run main.cs prints info: OrderService[0] and, indented below it, Placed an order for Tea.

  • info is the log level of LogInformation.
  • OrderService is the category, taken from ILogger<OrderService>.
  • Placed an order for Tea. is the message, with {Item} filled in.

The program never created the logger: the host did, and handed it to the constructor.

The command is the same in zsh, bash and PowerShell.

The Class Must Be Registered​

Without the AddTransient<OrderService>() line, the host doesn't know the class:

Output
Unhandled exception. System.InvalidOperationException: No service for type 'OrderService' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Program.<Main>$(String[] args) in /Users/you/demo/main.cs:line 10

Not with new​

Creating the class yourself with new OrderService() doesn't compile, because nothing passes the logger:

Output
/Users/you/demo/main.cs(4,27): error CS7036: There is no argument given that corresponds to the required parameter 'logger' of 'OrderService.OrderService(ILogger<OrderService>)'

The build failed. Fix the build errors and run again.

Let the host create the class, as in Step 1, and it creates the logger along with it.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting to register the classInvalidOperationException: No service for type 'OrderService' has been registered.builder.Services.AddTransient<OrderService>();
Creating the class with newerror CS7036: There is no argument given that corresponds to the required parameter 'logger'Get it from the host's services
Writing ILogger<SomethingElse>The log lines carry the wrong categoryUse the class's own name

Troubleshooting​

SymptomLikely causeFix
No service for type '...' has been registered.The class wasn't added to builder.ServicesRegister it before Build()
CS7036 ... required parameter 'logger'The class was created with newLet dependency injection create it

FAQ​

Why ILogger of the class, and not just ILogger?​

The type in the brackets becomes the category, which the console shows before each message: OrderService above. In a bigger app, that's how you know which class wrote a line, and how you set log levels per class.

Does this work in ASP.NET Core?​

Yes. The guide's own words name both hosts: "ASP.NET's WebApplication or Generic Host". In ASP.NET Core, WebApplication.CreateBuilder sets up the same dependency injection and logging.

Conclusion​

Ask for ILogger<YourClass> in the class's constructor, keep it in a readonly field, register the class in builder.Services, and let the host create it. Each line the class logs then carries its name as the category.

Additional Resources​