Search code examples
.netinversion-of-controlconstructor-injection

How to instantiate objects of classes that have dependencies injected?


Let's say I have some class with dependency injected:

public class SomeBusinessCaller {
   ILogger logger;
   public SomeBusinessCaller(ILogger logger) {
       this.logger = logger;
   }
}

My question is, how do I instantiate an object of that class? Let's say I have an implementation for this, called AppLogger. After I say

ObjectFactory.For<ILogger>().Use<AppLogger>();

how do I call constructor of SomeBusinessCaller? Am I calling

SomeBusinessCaller caller = ObjectFactory.GetInstance<SomeBusinessCaller>();

or there is a different strategy for that?


Solution

  • The code which uses caller does not live in a vacuum. Instead of assuming you need to create an instance of SomeBusinessCaller yourself, simply declare a dependency on it:

    public class SomeOtherClass
    {
        public SomeOtherClass(SomeBusinessCaller caller)
        {
            // ...
        }
    }
    

    The container will figure out that SomeBusinessCaller requires an ILogger, and it will automatically provide an instance of AppLogger.

    And, when something needs an instance of that class:

    public class YetAnotherClass
    {
        public YetAnotherClass(SomeOtherClass other)
        {
            // ...
        }
    }
    

    If you follow that logic for all the objects you write, eventually you will have exactly 1 object for which you actually request an instance:

    public static void Main()
    {
        // ...Initialize ObjectFactory...
    
        var compositionRootObject = ObjectFactory.GetInstance<YetAnotherClass>();
    
        compositionRootObject.DoYourThing();
    }