创建Driver时本来需要一个iAuto对应,sp回去容器里找;
由于之前注册了AddScoped(typeof(iAuto),typeof(BWM))
所以会自动创建一个BWM的实例传入Driver构造器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleApp14
{
class Program
{
static void Main(string[] args)//多态
{
//依赖反转:降耦合
ServiceCollection serviceDescriptors = new ServiceCollection();
//想开奥迪将bwm换成audi即可
serviceDescriptors.AddScoped(typeof(iAuto),typeof(BWM));
serviceDescriptors.AddScoped<Driver>();
ServiceProvider sp = serviceDescriptors.BuildServiceProvider();
//--------------------注册完成--------------------------
var man = sp.GetService<Driver>();
man.say();
}
}
interface iAuto
{
void run();
void race();
}
class BWM : iAuto
{
public void race()
{
Console.WriteLine("bwm race");
}
public void run()
{
Console.WriteLine("bwm is run");
}
}
class Audi : iAuto
{
public void race()
{
Console.WriteLine("audi race");
}
public void run()
{
Console.WriteLine("audi is run");
}
}
class Driver
{
private iAuto auto;
public Driver(iAuto iAuto)
{
this.auto = iAuto;
}
public void say()
{
auto.race();
auto.run();
}
}
}