dodyg / dodyg/practical-aspnetcore

Dependency Injection - register multiple implementations of the same Interface

Open
#123 6 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
10.4k
Forks
1.4k
PR merge metrics
No merged PRs in 30d

Description

In 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:

```c#
services.AddScoped();
services.AddScoped();

...

public interface IStrategy { }
public class StrategyA : IStrategy { }
public class StrategyB : IStrategy { }
...

public IStrategy LastRegisteredStrategy { get; }
public IEnumerable Strategies { get; }

public ValuesController(IStrategy lastRegisteredStrategy, IEnumerable 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
}
}
```

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.