开发者

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 d开发者_如何学运维ifferent strategy for that?


Depending on which DI Container you use, then yes: ask the container to provide you with an instance of SomeBusinessCaller.

The container should use auto-wiring to automatically figure out that the SomeBusinessCaller requires an instance of ILogger, and since AppLogger is registered, it can satisfy that requirement.

However, don't use the DI Container as a static Service Locator.

Instead, you should let the DI Container compose your entire dependency graph in one go in the application's Composition Root.


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜