Optional parameters with dependency injection

Is it possible to have an optional parameter for a constructor with dependency injection. I know that dependency injection usually it implies it is a required dependency, but for example if the only dependency is an ILogger, then I don't really care if one was registered or not. EDIT: Changed ILogger<Test> to be nullable
public class Test
{
private readonly ILogger<Test>? _logger;

public Test(ILogger<Test>? logger = null) // does this work?
{
_logger = logger
}

public void DoSomething()
{
_logger?.LogInformation("Doing something...");
}
}
public class Test
{
private readonly ILogger<Test>? _logger;

public Test(ILogger<Test>? logger = null) // does this work?
{
_logger = logger
}

public void DoSomething()
{
_logger?.LogInformation("Doing something...");
}
}
5 Replies
Angius
Angius5mo ago
You're injecting an ILogger<T> not ILogger<T>? so it cannot be null I mean, theoretically it can, if you want to write bad code But it shouldn't Also, unless you're doing some conditional registration (why?) then it will either be registered, or not, and you will know which it is So IMHO it doesn't make much sense to make it nullable
nathanAjacobs
nathanAjacobs5mo ago
Those are all fair, but what if this code is in a library, and it might not necessarily be used by dependency injection. So having it as an optional parameter might suit the situation where it is just being newed up manually
Angius
Angius5mo ago
I guess
nathanAjacobs
nathanAjacobs5mo ago
So if it exists in a library, I don't know if the consumer actually has an ILogger registered
not guilty
not guilty5mo ago
i would say optional parameters means passing putting it into a class in a nullable field but it depends on what it is
Want results from more Discord servers?
Add your server
More Posts