代码之家  ›  专栏  ›  技术社区  ›  Alex

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

  •  6
  • Alex  · 技术社区  · 16 年前

    (这个问题不依赖于特定的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();
    }
    

    我的问题是,你怎么把注射器送过来的?我通常只注册了自己的注入器,并将它注入到自己要注入的类型中,但我不确定这是否是正确的“模式”。

    2 回复  |  直到 16 年前
        1
  •  14
  •   matt b    16 年前

    你不应该把容器到处传递。

    App ,它允许您运行 app.Run() ,满足所有依赖关系。

        2
  •  2
  •   Community Mohan Dere    9 年前

    最好避免注射注射器。只需创建所需的类型,然后开始执行。我写了一篇关于这个话题的文章: Accessing the DI container

    推荐文章