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
5 Replies
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 nullableThose 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
new
ed up manuallyI guess
So if it exists in a library, I don't know if the consumer actually has an ILogger registered
i would say optional parameters means passing putting it into a class in a nullable field
but it depends on what it is