【问题标题】:Getting class instance from other project从其他项目获取类实例
【发布时间】:2018-01-09 11:56:09
【问题描述】:

我有一个这样的类库:

public class GoogleSearch
{
    private IGoogleApiHelper _googleApiHelper;

    public GoogleSearch(IGoogleApiHelper googleApiHelper)
    {
        _googleApiHelper = googleApiHelper;
    }
    //some methods
}

googleApiHelper 是从库的 IoC 容器中获得的服务。 我可以从库外部创建 GoogleSearch 类的实例,并从 IoC 容器中获取 googleApiHelper 服务吗?

【问题讨论】:

  • 我将它引用到项目并想调用它的方法。问题是我必须在构造函数中传递一个 IGoogleApiHelper 实例,但我希望它从 IoC 容器中获取
  • 如果你想创建GoogleSearch的新实例,那么你可以使用依赖解析器来获取IGoogleApiHelper并传递它。或者你可能会考虑使用依赖注入来解析GoogleSearch

标签: c# dependency-injection .net-core ioc-container


【解决方案1】:

googleApiHelper 是从库的 IoC 容器中获取的服务。

防止这样做。库不应使用 DI 容器,只有启动项目应具有对 DI 容器的引用,并应进行所有必需的注册,包括属于您的库的类型。如需更多信息,请阅读Composition Root

如果你遵循组合根模式,你不会有任何问题,因为一切都是在一个地方组合的。

【讨论】:

    猜你喜欢
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多