asp.net core 依赖注入
class Program { static void Main(string[] args) { new HomeController(new ServiceB()).print(); Console.ReadLine(); } } class HomeController { private IService _service; public HomeController(IService service) { _service = service; } public void print() { _service.output(); } } interface IService { public void output(); } class ServiceA : IService { public void output() { Console.WriteLine("AAA"); } } class ServiceB : IService { public void output() { Console.WriteLine("BBB"); } }
创建一个依赖注入容器
class Program { static void Main(string[] args) { //创建一个依赖注入容器(IServiceProvider) var service = new ServiceCollection().AddSingleton<IPerson, Teacher>().BuildServiceProvider().CreateScope().ServiceProvider; service.GetService<IPerson>();//Teacher构造 var a = service.GetService<IPerson>();//因为是单例模式所以不会再创建新实例 Console.WriteLine(a.GetType());//Teacher } } interface IPerson { } public class Student: IPerson { public Student() => Console.WriteLine("Student构造"); public string name="TOM"; public int age; } public class Teacher : IPerson { public Teacher() => Console.WriteLine("Teacher构造"); public string name; public int age; }