dodyg / practical-aspnetcore

Practical samples of ASP.NET Core 9 RC2, 8.0, 7.0, 6.0, 5.0, 3.1, 2.2, and 2.1,projects you can use. Readme contains explanations on all projects.
MIT License
9.44k stars 1.25k forks source link

Dependency Injection - register multiple implementations of the same Interface #123

Open neman opened 6 years ago

neman commented 6 years ago

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:

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 
      }
}
dodyg commented 6 years ago

Yes but please don't use MVC for the example. Stick to bare bone ASP.NET Core. We need to minimize the number of concepts that people need to know in any given examples.

neman commented 6 years ago

Yes, of course. This was just an example from the head. I will use middlewares, but than I cant inject services. I will retrieve them directly from the container.

Tratcher commented 6 years ago

Middleware can inject services in the constructor or in the Invoke method. https://github.com/aspnet/HttpAbstractions/blob/07d115400e4f8c7a66ba239f230805f03a14ee3d/src/Microsoft.AspNetCore.Http.Abstractions/Extensions/UseMiddlewareExtensions.cs#L89-L110

dodyg commented 6 years ago

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.

neman commented 6 years ago

@Tratcher I know I can inject service in custom middleware Invoke method (I did it many times). I was pointing out to app.Run or app.Use. If I’m going to use bare bone ASP.NET Core instead of MVC, than I should try to avoid building custom middleware also. If it's possible that would be great.

dodyg commented 6 years ago

I modified middleware-9 to demonstrate injection at Invoke as well (https://github.com/dodyg/practical-aspnetcore/commit/e852ef3bd385ab1a0b885ef2e39d12bb2b9bc875)