// As for Autofac, I think we just can use constructor injection not setter injection. // And I think Attribute injection is so complex. public static void Run() { Console.WriteLine($"开始运行{nameof(Demo3)}"); // 使用 StudentDal1 ContainerBuilder cb = new ContainerBuilder(); cb.RegisterType <StudentBll>().As <IStudentBll>(); cb.RegisterType <StudentDal1>().As <IStudentDal>(); IContainer container = cb.Build(); IStudentBll studentBll = container.Resolve <IStudentBll>(); IStudentDal studentDal = container.Resolve <IStudentDal>(); IEnumerable <Student> students = studentBll.GetStudents(); foreach (Student student in students) { Console.WriteLine(student); } // 使用 StudentDal2 cb = new ContainerBuilder(); cb.RegisterType <StudentBll>().As <IStudentBll>(); cb.RegisterType <StudentDal2>().As <IStudentDal>(); container = cb.Build(); studentBll = container.Resolve <IStudentBll>(); students = studentBll.GetStudents(); foreach (Student student in students) { Console.WriteLine(student); } Console.WriteLine($"结束运行{nameof(Demo3)}"); }
public void Run() { Console.WriteLine($"开始运行{nameof(FactoryTest)}"); var builder = new ObjectContainerBuilder(); builder.Register <StudentBll, IStudentBll>(); builder.Register <StudentDal1, IStudentDal>(); ICustomContainer container = builder.Build(); // 使用 StudentDal1 //IStudentBll studentBll = new StudentBll(new StudentDal1()); IStudentBll studentBll = container.Resolve <IStudentBll>(); var students = studentBll.GetStudents(); foreach (var student in students) { Console.WriteLine(student); } // 使用 StudentDal2 studentBll = new StudentBll(new StudentDal2()); students = studentBll.GetStudents(); foreach (var student in students) { Console.WriteLine(student); } Console.WriteLine($"结束运行{nameof(FactoryTest)}"); }