So, in your example, you have a Car that takes a HondaEngine, but in real life it doesn't really make sense to bind IEngine to HondaEngine. The whole point is that I might want to pass in a FordEngine or a ToyotaEngine.
So, now what?
I suspect I need to create an EngineFactory that I need to inject and then have it create the correct engine type outside the ctor. Is that right or is there a better way to do this?
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.
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
So, in your example, you have a Car that takes a HondaEngine, but in real life it doesn't really make sense to bind IEngine to HondaEngine. The whole point is that I might want to pass in a FordEngine or a ToyotaEngine.
So, now what?
I suspect I need to create an EngineFactory that I need to inject and then have it create the correct engine type outside the ctor. Is that right or is there a better way to do this?
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.
👍
That strategy pattern code is interesting. I had no idea you could do this:
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.