Creating objects with dependencies - dependency injection

前端 未结 3 1332
醉酒成梦
醉酒成梦 2021-01-06 11:21

Let\'s say we have class:

public class WithDependencies
{
  public WithDependencies(IAmDependencyOne first, IAmDependencyTwo second)
  // ...
}
3条回答
  •  粉色の甜心
    2021-01-06 11:39

    It depends on the context, so it's impossible to provide a single answer. Conceptually you'd be doing something like this from the Composition Root:

    var wd = new WithDependencies(new DependencyOne(), new DependencyTwo());
    

    However, even in the absence of a DI Container, the above code isn't always unambiguously the correct answer. In some cases, you might want to share the same dependency among several consumers, like this:

    var dep1 = new DependencyOne();
    var wd = new WithDependencies(dep1, new DependencyTwo());
    var another = AnotherWithDependencies(dep1, new DependencyThree());
    

    In other cases, you might not want to share dependencies, in which case the first option is more correct.

    This is just a small glimpse of an entire dimension of DI concerned with Lifetime Management. Many DI Containers can take care of that for you, which is one excellent argument to prefer a DI Container over Poor Man's DI.

    Once you start using a DI Container, you should follow the Register Resolve Release pattern when resolving types, letting Auto-wiring take care of the actual composition:

    var wd = container.Resolve();
    

    The above example assumes that the container is already correctly configured.

提交回复
热议问题