哪些策略可以在库中使用 IoC 容器?

发布于 2024-10-29 01:09:26 字数 1431 浏览 5 评论 0原文

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

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

发布评论

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

评论(3

悍妇囚夫 2024-11-05 01:09:26

依赖注入(控制反转)是一组可用于编写松散耦合代码的原则和模式。前提是代码是松耦合的。 DI 容器不会使您的代码松散耦合

您需要找到一种方法将 UI 呈现与 UI 逻辑分离。有很多演示模式描述了如何做到这一点:模型视图控制器模型视图呈现器演示模型等。

一旦有了良好的解耦,DI(和容器)就可以用来组成协作者。

Dependency Injection (Inversion of Control) is a set of principles and patterns that you can use to compose loosely coupled code. It's a prerequisite that the code is loosely coupled. A DI Container isn't going to make your code loosely coupled.

You'll need to find a way to decouple your UI rendering from UI logic. There are lots of Presentation Patterns that describe how to do that: Model View Controller, Model View Presenter, Presentation Model, etc.

Once you have good decoupling, DI (and containers) can be used to compose collaborators.

静谧幽蓝 2024-11-05 01:09:26

由于库不应该对 ioc 框架本身有任何依赖,因此我们将 spring.net ioc 配置 xml 文件包含在该库的标准配置中。理论上这是模块化的,因为每个 dll 都有自己的子配置。然后将所有子配置组装起来,成为主配置的一部分。

但实际上,这种方法很容易出错并且相互依赖性太强:一个库配置必须了解其他库的属性以避免重复。

我的结论是:要么使用@Chris Ballard“穷人的依赖注入”,要么处理主应用程序的大而丑陋的紧密耦合配置模块中的所有依赖项。

Since the library should not have any dependency on the ioc framework itself we included spring.net ioc config xml-files with the standard configuration for that lib. That was modular in theory because every dll had its own sub config. All sub-configs were then assembled to become a part of the main confing.

But in reality this aproach was error prone and too interdependent: one lib config had to know about properties of others to avoid duplicates.

My conclusion: either use @Chris Ballard "poor man's dependency injection" or handle all dependencies in on big ugly tightly coupled config-module of the main app.

筱武穆 2024-11-05 01:09:26

根据您的框架的复杂程度,您可能会摆脱基于手动编码构造函数的依赖项注入,使用无参数默认构造函数(使用正常的具体实现),但使用第二个构造函数来注入依赖项以用于单元测试目的,例如。

private IMyDependency dependency;

public MyClass(IMyDependency dependency)
{
    this.dependency = dependency;
}

public MyClass() : this(new MyDefaultImplementation())
{

}

Depending on how complex your framework is, you may get away with handcoding constructor based dependency injection, with a parameterless default constructor (which uses the normal concrete implementation) but with a second constructor for injecting the dependency for unit test purposes, eg.

private IMyDependency dependency;

public MyClass(IMyDependency dependency)
{
    this.dependency = dependency;
}

public MyClass() : this(new MyDefaultImplementation())
{

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