依赖注入:如何各地通过注入容器? [英] Dependency injection: How to pass the injection container around?

查看:113
本文介绍了依赖注入:如何各地通过注入容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这个问题并不依赖于特定的IoC框架,所以我的样品中的接口和类型元类型,只要有合适的类型在你的头上你最喜欢的IoC框架取代他们。)

(This question does not rely on a specific IoC framework, so the interfaces and types in my samples are meta-types. Just replace them with the appropriate types for your favorite IoC framework in your head.)

在我的主要方式,我通常会设置为我的容器做这样的事情:

In my main methods, I typically set up my container doing something like this:

static void Main()
{
    IInjector in = new Injector();
    in.Register<ISomeType>().For<SomeType>();
    in.Register<IOtherType().For<OtherType>();
    ...

    // Run actual application
    App app = in.Resolve<App>();
    app.Run();
}

我的问题是,你如何获得注射器派人四处?我通常只是注册了喷油器与自己,把它注入到自己会做注射的类型,但我不知道这是正确的模式。

My question is, how do you get the Injector sent around? I've normally just registered the injector with itself and had it injected into types that themselves are going to do injection, but I'm not sure if this is the proper "pattern".

推荐答案

您应该无法通过容器周围。

You shouldn't pass the container around.

相反,你的入口点/主方法要求的容器,它需要上手的对象 - 比如你的应用程序对象/豆。容器然后返回连接到应用,它允许您运行 app.Run(),拥有完整的对象图所有的依赖性来满足。

Instead, your entry-point/main method asks the container for the objects it needs to get started - such as your App object/bean. The container then returns the full object graph connected to App, which allows you to run app.Run(), with all the dependencies satisfied.

这是一个有点反模式的对象,要注意容器的,或者是每个对象要求的容器,它的依赖 - 如果你这样做,那么你的没有的倒控制和你有什么不依赖注入 - 你仍然有对象,要求他们需要什么,而不是给予他们所需要的。

It's a bit of an anti-pattern for the objects to be aware of the container, or for each object to be asking the container for it's dependencies - if you do this then you have not inverted control and what you have is not dependency injection - you still have objects asking for what they need, rather than being given what they need.

这篇关于依赖注入:如何各地通过注入容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆