.net core IOC(控制反转)、DI(依赖注入)

一、什么是控制反转(Inversion of Control ,简称IOC)

控制反转,是面向对象编程中的一种设计原则,可以减少代码之间的耦合度,其中最常见的方式叫做依赖注入(Dependency Injection , 简称DI)

1.IOC代码层面解释:

调用者不在创建(不自己new)被调用者的实例,而是交给容器去创建,这个就是控制反转

2.DI代码层面解释:

容器创建好实例在注入调用者的过程,就是依赖注入(比如:属性注入、构造函数注入等)。

二、为什么要使用IOC

我们常用的设计模式为接口驱动设计,接口驱动设计有很多好处,提供不同灵活的子类实现,
但是接口一定是需要实现的,也就是初始化实例一定会执行,
所以就会出现一些问题:多个子类按照一般的方法实现同一个接口,即会出现耦合

1.测试代码(耦合代码)

第一步: 新建一个.net core API程序ioc_demo

第二步:创建一个接口:ITestService.cs

using System;
namespace ioc_demo.@interface
{
    public interface ITestService
    {
        //声明一个属性一个方法
        int Count { get; }
        void Add();
    }
}

第三步:新建一个实现接口的类:TestServiceImpl.cs

using System;
using ioc_demo.@interface;

namespace ioc_demo.lmpl
{
    public class TestServiceImpl : ITestService
    {
        private int _count;
        public TestServiceImpl()
        {
            _count = 0;
            Console.WriteLine("服务创建");
        }

        public int Count => _count;

        public void Add()
        {
            _count++;
        }
    }
}

第四步:创建一个新的control:TestController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ioc_demo.@interface;
using ioc_demo.lmpl;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ioc_demo.Controllers
{
    [Route("api/[controller]")]
    public class TestController : Controller
    {
        // GET: api/values
        [HttpGet]
        public Tuple<int,int> Get()
        {
            ITestService testService = new TestServiceImpl(); //接口实现类,程序耦合
            int first = testService.Count;
            testService.Add();
            int second = testService.Count;
            Console.WriteLine(first);
            Console.WriteLine(second);
            return new Tuple<int, int>(first, second);

        }
    }
}

三、IOC如何降低耦合

1.情景再现:

两个类互相调用,一般情况ClassA中使用带了ClassB中的对象或者属性方法,那么就需要在ClassA中显式的new一个ClassB

2.IOC实现原理

采用依赖注入技术之后,ClassA的代码只需要定义一个私有的ClassB对象,不要用通过实例化new出来这个ClassB,而是通过相关的容器控制程序将ClassB对象在容器中new出来并注入到ClassA类里的引用中。 具体的获取方法、对象获取时的状态则需要配置来制定

四、 IOC模式中的容器

1.容器的解释

IOC模式,系统通过引入实现了IOC模式的IOC容器,即可由IOC容器来管理对象的生命周期、依赖关系、从而使得应用程序的配置和依赖性规范与实际的应用程序代码分离。
最大的好处:修改程序组件间的配置,而不需要重新修改编译具体的代码

2. .net core 自带容器的使用

  1. AddTransient:瞬时的,每次访问构造一个

Startup.csConfigureServices中添加以下代码

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddTransient<ITestService, TestServiceImpl>();//注入服务 瞬时模式
        }

TestController.cs中代码替换为下列代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ioc_demo.@interface;
using ioc_demo.lmpl;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ioc_demo.Controllers
{
    [Route("api/[controller]")]
    public class TestController : Controller
    {
        private ITestService _service;
        public TestController(ITestService testService)
        {
            _service = testService;
        }
        // GET: api/values
        [HttpGet]
        public Tuple<int,int> Get()
        {
            //ITestService testService = new TestServiceImpl(); //接口实现类,程序耦合
            int first = _service.Count;
            _service.Add();
            int second = _service.Count;
            Console.WriteLine(first);
            Console.WriteLine(second);
            return new Tuple<int, int>(first, second);

        }
    }
}

总结:每次访问接口,TestServiceImpl构造函数中都会执行Console.WriteLine("服务创建"); 符合瞬时创建构造函数的特性

  1. AddSingleton: 单例,全局只有一个

    Startup.csConfigureServices中替换以下代码

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSingleton<ITestService, TestServiceImpl>(); //注入服务  单例模式
        }

总结:每次访问接口,TestServiceImpl构造函数中都只会执行Console.WriteLine("服务创建");一次, 符合单例模式的特性

  1. AddScoped : 在同作用域、服务每次请求只创建一个

Startup.csConfigureServices中添加以下代码

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddScoped<ITestService, TestServiceImpl>();//注入服务 作用域模式
        }

TestController.cs中代码替换为下列代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ioc_demo.@interface;
using ioc_demo.lmpl;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ioc_demo.Controllers
{
    [Route("api/[controller]")]
    public class TestController : Controller
    {
        private ITestService _service;
        public TestController(ITestService testService)
        {
            _service = testService;
        }
        // GET: api/values
        [HttpGet]
        public Tuple<int,int> Get([FromServices]ITestService service)
        {
            //ITestService testService = new TestServiceImpl(); //接口实现类,程序耦合
            service.Add();
            int first = _service.Count;
            _service.Add();
            int second = _service.Count;
            Console.WriteLine(first); 
            Console.WriteLine(second);
            //如果返回1,2  说明service 与 _service是同一个对象
            return new Tuple<int, int>(first, second);

        }
    }
}

总结:在此作用域使用服务,只会创建一个;

  • 6
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
控制反转(Inversion of Control,IoC)和依赖注入(Dependency Injection,DI)是面向对象编程中的两个重要概念。它们可以帮助我们更好地实现代码的松耦合,提高代码的可维护性和可扩展性。 IoC是一种编程思想,它将程序的控制权从程序员手中转移到了IoC容器中,由IoC容器来管理和调用对象之间的依赖关系。IoC容器就像是一个工厂,它负责创建和管理对象,程序员只需要告诉IoC容器需要哪些对象,IoC容器就会根据配置文件或者注解等方式来创建对象,并将它们组合起来。 DIIoC的一种具体实现方式,它通过构造函数、属性或者方法等方式将依赖关系注入到对象中。当一个对象需要另一个对象时,它不会直接创建这个对象,而是通过IoC容器来获取这个对象。通过DI,我们可以实现对象之间的松耦合,提高代码的可维护性和可测试性。 下面是一个简单的例子,演示如何使用IoC容器和DI实现对象之间的依赖注入: ```java // 定义接口 public interface MessageService { void send(String message); } // 实现接口 public class EmailService implements MessageService { public void send(String message) { System.out.println("Email sent: " + message); } } // 定义需要依赖注入的类 public class MyClass { private MessageService messageService; // 通过构造函数注入依赖 public MyClass(MessageService messageService) { this.messageService = messageService; } public void doSomething() { // 使用依赖的方法 messageService.send("Hello World!"); } } // 使用IoC容器创建对象并注入依赖 public class Main { public static void main(String[] args) { // 创建IoC容器 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 从IoC容器中获取对象 MyClass myClass = (MyClass) context.getBean("myClass"); // 调用方法 myClass.doSomething(); } } ``` 在上面的例子中,我们定义了一个MessageService接口和一个EmailService实现类。然后我们定义了一个MyClass类,它需要依赖MessageService对象来完成一些操作。通过构造函数注入依赖,我们可以将MessageService对象注入到MyClass中。最后,在使用IoC容器创建对象时,我们可以通过配置文件或者注解等方式来指定依赖的实现类,IoC容器会自动创建对象并注入依赖。 总之,IoCDI是非常重要的编程思想,它们可以帮助我们更好地管理对象之间的依赖关系,提高代码的可维护性和可扩展性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

与诸君共勉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值