为什么说DI解耦

为什么说IOC/DI(控制反转/依赖注入)降低耦合

public class HomeController : Controller
    {
        private readonly IStudentReponstory _studentReponstory;
	////使用构造函数的方式注入 IStudentReponstory
    //public HomeController(IStudentReponstory studentReponstory)
    //{
    //    _studentReponstory = studentReponstory;
    //}
    public HomeController()
    {
        //在构造函数中直接实例化服务而不是通过接口注入
        _studentReponstory = new MockStudentReponstory();
    }

    public string Index()
    {
        return _studentReponstory.GetStudentById(1).name;
    }
}

​ 以上述的一个demo为例,传统用new直接实例化的方式,会使 HomeControllerMockStudentReponstory 紧密耦合,如果我想使用新的 IStudentReponstory 接口实例,如:SqlStudentReponstoryDatabaseStudentReponstory 我必须要在 HomeController 中修改代码,将 new MockStudentReponstory() 改为 new SqlStudentReponstory()new DatabaseStudentReponstory () 。这还只是一个控制器,如果是项目中的控制器都这样直接实例化,那意味着我需要在每个控制器中修改代码,想想都可怕

​ 而以依赖注入的方式,在构造函数中注入接口而不是具体实现,意味着我们如果需要改变实例方法,只需要修改接口对应的服务一个地方就行,而不是到具体的控制器中修改。以.net core 为例,我们只需要修改Startup.cs文件中注册的服务就行

posted @ 2021-11-03 16:43  慕枫三生  阅读(92)  评论(0)    收藏  举报