Dependency Injection - register multiple implementations of the same Interface
See original GitHub issueIn the DI section I found your comment
Note: example 2 is forthcoming. The inspiration has not arrived yet.
Is this good enough for an example? I can make an example and PR something like this:
services.AddScoped<IStrategy, StrategyA>();
services.AddScoped<IStrategy, StrategyB>();
...
public interface IStrategy { }
public class StrategyA : IStrategy { }
public class StrategyB : IStrategy { }
...
public IStrategy LastRegisteredStrategy { get; }
public IEnumerable<IStrategy> Strategies { get; }
public ValuesController(IStrategy lastRegisteredStrategy, IEnumerable<IStrategy> strategies)
{
LastRegisteredStrategy = lastRegisteredStrategy;
Strategies = strategies;
var strategyA = Strategies.FirstOrDefault(x => x.GetType() == typeof(StrategyA));
var strategyB = Strategies.FirstOrDefault(x => x.GetType() == typeof(StrategyB));
if (strategyB.GetType() == LastRegisteredStrategy.GetType())
{
//log
}
}
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (5 by maintainers)
Top Results From Across the Web
How to register multiple implementations of the same ...
When I call the _serviceProvider.GetService() method, I cannot inject data into the constructor. For example consider this: public class ...
Read more >NET – Dependency Injection, One Interface and Multiple ...
In programming world, it is very common to have multiple implementations of the same interface. Most commonly used pattern is Factory ...
Read more >Use multiple implementations of an interface in ASP.NET ...
Using dependency injection with multiple implementations of an interface in ASP.NET Core · Use an IEnumerable collection of service instances.
Read more >.NET6 Dependency Injection — One Interface, Multiple ...
You want to have multiple implementations with the same interface. In this article, I will show you how. One friendly approach could be ......
Read more >Multiple implementations of same interface - the options
Different methods of registering the same interface with multiple implementations using .NET dependency injection.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I modified
middleware-9
to demonstrate injection atInvoke
as well (https://github.com/dodyg/practical-aspnetcore/commit/e852ef3bd385ab1a0b885ef2e39d12bb2b9bc875)Nice.
@Tratcher https://github.com/dodyg/practical-aspnetcore/blob/master/projects/middleware-9/src/Program.cs shows construction injection service. It should be modified to show injection at the Invoke method as well.