Services in DI container is by default required. To make it optional, give it a defualt value.
Assuming ConsumerService
rely on AnotherService
while AnotherService
is not registered in DI container.
Having a default value for the optional service.
public class ConsumerService
{
private readonly AnotherService? _dep;
public ConsumerService(AnotherService? dep = null) // Works. Optional service that **has a default value** of null.
{
_dep = dep;
}
}
These won't work, and will cause crash upon resolving the service:
public class ConsumerService
{
private readonly AnotherService _dep;
public ConsumerService(AnotherService dep) // Any service by default is required.
{
_dep = dep;
}
}
public class ConsumerService2
{
private readonly AnotherService? _dep;
public ConsumerService2(AnotherService? dep) // Only have null annotation is not enough, still cause exception.
{
_dep = dep;
}
}