DEV Community

Discussion on: .NET Core Dependency Injection: Everything You Ought To Know

Collapse
 
jamesmh profile image
James Hickey

in real life it doesn't really make sense to bind IEngine to HondaEngine

Well, in some cases it might make sense. If you were, for example, building a multi-tenant / white-label app for the automotive industry (which I've done before) it might make sense to bind a concrete implementation of IEngine at app startup.

But yes, in other cases, when using late binding, then a factory could work.

You could also use the strategy pattern in conjunction with the DI container.

👍

Collapse
 
timothymcgrath profile image
Timothy McGrath

That strategy pattern code is interesting. I had no idea you could do this:

services.AddScoped<IMathOperator, AddOperator>();
services.AddScoped<IMathOperator, SubtractOperator>();
services.AddScoped<IMathOperator, MultipleOperator>();
services.AddScoped<IMathOperator, DivideOperator>();
Thread Thread
 
jamesmh profile image
James Hickey

It's pretty neat! As long as your interface exposes some way to differentiate between each concrete implementation then you can just check that at run-time.