Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Last active October 25, 2022 03:41
Show Gist options
  • Save xiaomi7732/d4e9b023609322d0414a3790e3df625d to your computer and use it in GitHub Desktop.
Save xiaomi7732/d4e9b023609322d0414a3790e3df625d to your computer and use it in GitHub Desktop.
Make an optional service in .NET DI

Make an optional service in .NET DI Container

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.

Solution

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:

Mistake #1

public class ConsumerService
{
    private readonly AnotherService _dep;

    public ConsumerService(AnotherService dep)  // Any service by default is required.
    {
        _dep = dep;
    }
}

Mistake #2

public class ConsumerService2
{
    private readonly AnotherService? _dep;

    public ConsumerService2(AnotherService? dep) // Only have null annotation is not enough, still cause exception.
    {
        _dep = dep;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment