IoC和依赖注入的效用 [英] Utility of IoC and Dependency Injection

查看:74
本文介绍了IoC和依赖注入的效用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些情况测试不适用于该项目。

There are some cases in which unit test don't work for the project.

我正在研究控制反转和依赖注入实用程序,我想知道是否有充分的理由使用它

I'm studing the Inversion of Control and Dependency Injection utilities and I would like to know if there are good reasons for use it than for make unit tests easier.

-更新

好,让我们分析1的优点:较少的耦合。
您从子类型中删除了耦合,然后将耦合添加到需要创建要注入的对象的处理程序类型。

Ok, let's analysis 1 of the cited advanteges: less coupling. You take out the coupling from the child type, and you add coupling to the handler type who need to create the objects to inject.

没有单元测试,

推荐答案

IOC / DI为您的应用程序带来了一些非常重要的功能

IOC/DI bring some very important features to your application


  • 可插入性:使用DI可以将依赖项注入代码中,而无需明确知道功能的实际工作方式。
    例如:您的类可能会注入ILog接口,以便可以编写日志。由于该类与ILog接口一起使用,因此有可能实现FileLog,MemoryLog或DatabaseLog&将此注入您的班级。只要实现ILog接口,这些实现都可以正常工作

  • Testability :在您的类中使用DI时,您可以注入模拟对象来测试行为类,而无需实际实现。
    例如:考虑一个需要存储库来执行数据操作的Controller类。在这种情况下,存储库可以是控制器的DI。如果您需要在Controller类上编写测试,则可以通过DI'd模拟版本的存储库,而不必使用实际的存储库类

  • 可配置性:一些常见的DI框架(例如Castle Windor,Unity,Spring等)允许进行DI以及对创建对象的生命周期进行管理。这是一项非常强大的功能,允许您管理依赖关系&通过配置延长它们的寿命。例如,考虑您的应用程序需要ICache依赖关系。通过终生配置对象管理,您将能够将缓存配置为每个应用程序,每个会话或每个请求等,而不必在代码中显式烘焙实现。

  • Plugability: with DI you can inject dependency into the code without explicitly knowing how the functionality is actually working. For example: your class might get a ILog interface injected so that it can write logs. Since the class works with the ILog interface, it would be possible to implement a FileLog, MemoryLog or a DatabaseLog & inject this into your class. Any of these implementation will work fine as long as they implement the ILog interface
  • Testability: With DI in your class, you can inject mock objects to test the behaviour of your class without actually needing the concrete implementation. For example: consider a Controller class which needs a Repository to perform data operations. In this case, the repository can be DI for the controller. If you need to write tests on the Controller class, you can pass a DI'd mock version of the repository without having to work with the actual repository class
  • Configurability: Some of the common DI frameworks like Castle Windor, Unity, Spring etc., allow doing DI along with lifetime management of the object created. This is a very powerful feature & allow you to manage the dependencies & their lifetime via configuration. For example consider your application needs a ICache dependency. Via the configuration for lifetime & object management, you will be able to configure the cache to be a Per-application or per-session or per-request etc. without having to explicitly bake the implementation in your code.

HTH

这篇关于IoC和依赖注入的效用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆