using Autofac; namespace autofac构造函数注入; internal class Program { static void Main(string[] args) { //创建一个容器 ContainerBuilder builder = new ContainerBuilder(); //注册UserService builder.RegisterType<UserService>().As<IUserService>(); builder.RegisterType<Student>(); //从容器中解析出UserService IContainer container = builder.Build(); //IUserService a = container.Resolve<IUserService>(); ////执行UserService的方法 //a.show(); var student = container.Resolve<Student>(); student.show(); } } //生产一个 UserService类 public class UserService : IUserService { public void show() { Console.WriteLine("UserService 执行"); } } public interface IUserService { void show(); } //生成一个学生类 public class Student { IUserService _userService; public Student(IUserService userService) { _userService= userService; } public void show() { Console.WriteLine("Student 执行"); _userService.show(); } }