依赖注入:如何传递注入容器?

发布于 2024-08-26 14:44:19 字数 476 浏览 7 评论 0原文

(这个问题不依赖于特定的 IoC 框架,因此我的示例中的接口和类型都是元类型。只需将它们替换为您脑海中最喜欢的 IoC 框架的适当类型即可。)

在我的主要方法中,我通常设置我的容器做这样的事情:

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

我的问题是,如何发送注射器?我通常只是向其自身注册注入器,并将其注入到本身要进行注入的类型中,但我不确定这是否是正确的“模式”。

(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".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偏爱你一生 2024-09-02 14:44:19

您不应该传递容器。

相反,您的入口点/主方法会向容器询问启动所需的对象 - 例如您的 App 对象/bean。然后,容器返回连接到 App 的完整对象图,这允许您在满足所有依赖项的情况下运行 app.Run()

对于对象了解容器,或者每个对象向容器询问其依赖项,这有点反模式 - 如果你这样做,那么你就没有反向控制,并且什么你所拥有的不是依赖注入——你仍然有对象询问他们需要什么,而不是被给予他们需要什么。

You shouldn't pass the container around.

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.

夏至、离别 2024-09-02 14:44:19

最好避免注射注射器。只需创建您需要的类型,然后开始执行。我已经就此主题写了一篇较长的文章:访问 DI 容器

It's best to avoid injecting the injector. Just create the types you need, and then start executing. I've written a somewhat longer post on this topic: Accessing the DI container

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文