关于Ioc和DI前两天写了一个关于自己的理解的文章,有的朋友说需要一个例子能更好的解释,今天就来发一个
例子是一个Console程序,我自定义了四个类和一个接口,分别为Employee,GetRealNameCommand,GetNickNameCommand,Company,接口为ICommand。
Employee只有两个属性RealName和NickName,ICommand也只有一个方法Execute来处理Employee,具体怎么操作,由子类定义。
具体的两个Command类分别获取Employee的NickName和RealName。
Company类内部包含一个Employee的List和一个DoExecute方法,具体执行什么,由我们的程序指定。
class Company : IDisposable
{
private List<Employee> persons = new List<Employee>();
private ICommond command;
public void DoExecute()
{
if(command != null)
{
foreach (Employee person in persons)
{
command.Execute(person);
}
}
}
public interface ICommond
{
void Execute(Employee person);
}
public class GetNickNameCommand : ICommond
{
public void Execute(Employee person)
{
Console.WriteLine(person.NickName);
}
}
public class GetRealNameCommand : ICommond
{
public void Execute(Employee person)
{
System.Console.WriteLine(person.RealName);
}
}
我们首先看一下Main方法中是怎么执行的,
static void Main(string[] args)
{
Console.WriteLine("The setter inject......");
using (Company company = new Company())
{
company.Persons.AddRange(new Employee[]
{
new Employee("MyNickName","MyRealName"),
new Employee("YourNickName","YourRealName"),
}
);
GetNickNameCommand getNickNameCommand = new GetNickNameCommand();
Console.WriteLine("The first inject......\r\n Get the person's NickName");
这里就可以理解为注入
company.Command = getNickNameCommand;
这里就是一个我理解的Ioc的控制反转
company.DoExecute();
Console.ReadLine();
Console.WriteLine("The second inject......\r\n Get the person's RealName");
GetRealNameCommand getRealNameCommand = new GetRealNameCommand();
这里就可以理解为注入
company.Command = getRealNameCommand;
这里就是一个我理解的Ioc的控制反转
company.DoExecute();
Console.ReadLine();
}
Console.WriteLine("The constructor inject......");
这里就可以理解为注入(构造器注入),这种注入无法多次调整
using (Company company = new Company(new GetNickNameCommand()))
{
company.Persons.AddRange(new Employee[]
{
new Employee("MyNickName","MyRealName"),
new Employee("YourNickName","YourRealName"),
}
);
Console.WriteLine("The first inject...... \r\n Get the person's NickName");
company.DoExecute();
Console.ReadLine();
}
}
关于接口注入的方式,我还是认为应该结合构造器和Setter两种方式来配合使用,如果有朋友有更好的理解,希望能给一个关于接口注入的例子。