Autofac 之一 概述

一、引言

IOC(控制反转),就是一种程序的设计思想,先了解几个基本的概念

  • 依赖:就是一个类依赖于另一个类

  • 依赖倒置原则:高层模块不应该依赖于低层模板,而是依赖于低层的抽象,两者应该依赖于抽象
  • IOC(控制反转):把高层对低层的依赖交个第三方,可以是IOC容器,也可以是工厂,要什么对象给什么对象(比如工厂模式+配置文件)
  • DI依赖注入:实现IOC的一种方式、手段
  • IOC容器:依赖注入的框架,用来映射依赖,管理对象的创建和生命周期

二、依赖注入

将对象的创建和绑定转移到被依赖对象的外部来实现

  • 构造函数注入
interface ICar
{
    string Show();
} 
class BMW:ICar
{
    public string Show()
    {
        return "宝马";
    }
}
class ChinesePeopleContructor 
{
    private ICar _car;
    public ChinesePeopleContructor(ICar bmw)
    {
        _car = bmw;
    }
    public void Run()
    {
        Console.WriteLine($"今天开{_car.Show()}上班");
    }
}
static void Main(string[] args)
{
    ICar car = new BMW();
    ChinesePeopleContructor people = new ChinesePeopleContructor(car);
    people.Run();
    Console.Read();
}
  • 属性注入
interface ICar
{
    string Show();
}
class BMW:ICar
{
    public string Show()
    {
        return "宝马";
    }
}
class ChinesePeopleProperty
{
    private ICar _ICar;
    public ICar IC
    {
        get { return _ICar; }
        set { _ICar = value; }       
    }
    public void Run()
    {
        Console.WriteLine($"今天开{_ICar.Show()}上班");
    }
}
static void Main(string[] args)
 {
     ICar car = new BMW();
     ChinesePeopleProperty people = new ChinesePeopleProperty();
     people.IC = car;
     people.Run();
     Console.Read();
 }
  • 接口注入
interface ICar
{
    string Show();
}
 class BMW:ICar
{
    public string Show()
    {
        return "宝马";
    }
}
 interface IDependent
{
    void SetDependent(ICar icar);
}
class ChinesePeopleInterface : IDependent
{
    private ICar _ICar;
    public void SetDependent(ICar icar)
    {
        _ICar = icar;
    }
    public void Run()
    {
        Console.WriteLine($"今天开{_ICar.Show()}上班");
    }
}
static void Main(string[] args)
{        
      ICar car = new BMW();
      ChinesePeopleInterface people = new ChinesePeopleInterface();
      people.SetDependent(car);
      people.Run();
      Console.Read();    
}

六、IOC容器

IOC容器是一个DI框架:

  1. 动态创建、注入依赖对象;

  2. 管理对象生命周期

  3. 映射依赖关系

常见的IOC容器:Spring.NET,Castle Windsor, Ninject,Autofac,Unity等等 。。。

猜你喜欢

转载自www.cnblogs.com/PenZ/p/10318020.html