dotnet / dotnet/core

[Feature Request] Support Multiple Implementations of an Interface in .NET Core Dependency Injection

Open
#8,333 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
PowerShell
Stars
22k
Forks
4.9k
Avg merge
5d 5h
Merged PRs (30d)
29

Description

Currently, when using .NET Core's built-in dependency injection framework, only one implementation of an interface can be registered in the program.cs layer. However, in some cases, it may be desirable to have multiple classes implementing the same interface registered and available for use in the software.

The proposed feature would allow multiple implementations of an interface to be registered in the program.cs layer for dependency injection, while also providing a way to determine which implementation is being used at runtime. One possible approach would be to introduce a new attribute, such as [InjectAs], which could be applied to each implementation of the interface to indicate which implementation should be used at runtime.

To implement this approach, each implementation of the interface would be decorated with the [InjectAs] attribute, specifying a unique identifier for the implementation. When requesting an instance of the interface through dependency injection, the identifier could be passed as a parameter to the DI container. The DI container would then use the identifier to retrieve the corresponding implementation of the interface.

By allowing multiple implementations of an interface to be registered in the program.cs layer, .NET Core developers would have greater flexibility in designing and implementing their software. This feature would also make it easier to switch between different implementations of an interface without having to modify the code itself, which would make the software more modular and easier to maintain over time. The use of an attribute to specify the implementation at runtime would provide a convenient and intuitive way to control which implementation is used in different parts of the application.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.