【问题标题】:Static dependency injection factory, right or wrong?静态依赖注入工厂,对还是错?
【发布时间】:2014-04-02 05:14:57
【问题描述】:

最近,当我在我正在进行的项目中尝试使用 Ninject 时,我遇到了障碍。

我经历了各种各样的问题,系统地要求我的设计和架构支持依赖注入。

  1. Is this right to inject the container/kernel to the main application presenter?

  2. How to configure Ninject to use along with NHibernate in WinForms?

  3. Conditional dependency injection binding only when property not null

  4. What did I get wrong, DI or Design, and how should I go about it?

经过数小时、数小时、数小时的搜索,我看到了 Justin Etheredge 的那篇文章,他谈到了他的静态 DIFactory 类。

我现在想知道,使用静态 DI 工厂不是让事情像魔术一样工作吗?

我想了解在实际应用程序中使用静态 DI 工厂的优缺点。

另外,IoC 和 DI 是否相同,或者它们非常相似,但存在一些差异?

【问题讨论】:

    标签: c# architecture dependency-injection inversion-of-control


    【解决方案1】:

    static DI Factory is a Service LocatorService Locator is an anti-pattern,因为这会使 难以推理您的代码

    Service Locator 的唯一优点是它 easier to understand than Dependency Injection。但是,DI 并不难掌握once you get over a few conceptual hurdles

    IoC 和 DI 的关系是DI is a special case of IoC

    【讨论】:

    • 如果某些类型在应用程序启动时无法实例化,因为它们需要用户凭据才能正确实例化怎么办?例如,NHibernante.ISessionFactory 就是这样一个问题,如果没有正确的连接字符串,它就无法实例化,并且一旦创建,它就不会让人改变它的连接字符串。作为一种解决方法,可以提供一个IDbConnection,并丢失二级缓存,该二级缓存在整个ISession 生命周期中保存对象的跟踪。然后需要用户提供他的凭据,现在ISessionFactory 依赖不再是问题。
    • AbstractFactory 允许注册新类型吗?你会怎么做?
    • 如果你不能在运行时解析一个子图,你总是可以添加另一个间接层。抽象工厂将是一种选择。这里有更多关于implementing an Abstract Factory的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 2023-03-20
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-21
    相关资源
    最近更新 更多