ISomethingto the class
SomeImplementation, you can also use
typeof(T)as an argument instead of the generic method used above. I am just making up the scenarios but hopefully you can visualize the interface and the class which implements it, in-case not here is how it would look:
ISomethingclass for you, as we told it whenever you see
ISomethingpass it a
Something. As mentioned almost all DI frameworks has the notion of this, and it is usually known as Bind or Register.
ISomethingresolved. So for example if we had 3 classes with a dependency on
ISomethingthere would be 3 instances of
Somethingcreated. This may be fine however in some situations you may want to have only 1 instance of a given class.
Somethingfor every dependency. This here allows us to have an object which acts like a singleton but without any of the downsides. As mentioned in the previous chapters there is rarely a need for singleton and static classes explicitly when you use DI correctly, making your classes a lot less coupled and far easier to test as this is moved to be a configuration concern.
There are far more binding scenarios, some are specific to the game dev world (such as binding to prefabs, methods, gameobjects with Zenject) an some are specific to the web dev world, ultimately you can read up more on this for each DI framework on their sites.
You almost always want to use constructor injection because it means your objects are unaware of the DI framework, i.e if you want to use property injection you often have to put an attribute on your property, and this property means you have to add
using SomeDIFrameworkwhich makes that model and everything that uses it dependent upon a specific DI framework. You ideally do not want to fall into this trap as it is like a virus that spreads.
This is not 100% what is happening as the actual reflection may sometimes happen up front, sometimes at resolve time, and also in some cases it may have other metadata around how it should handle bindings, but for all intents and purposes this is accurate enough for you to get your head around what is happening under the hood.
Bind<ISomething>().To<Something>().InSingletonScope()the container would only instantiate the implementation for
ISomethingonce and then every time it was needed (be it directly or as a dependency in another class) it would just return back that existing implementation. This basically allows you to have singleton style instances without coding it as a singleton (see anti-patterns for topic on why singletons are iffy).
Controllerclasses be registered within MVC so all you need to handle is the binding aspect. Same sort of thing in Unity with Zenject you just give it a project/scene context and your installers and off it goes, automatically resolving all your parts for you.