SeverCollection IOC的例子

SeverCollection IOC在Nuget上搜索microsoft.extensions.dependencyinjection

1.一个简单的代码例子:

private static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");

        //定义一个IOC容器
        ServiceCollection services = new ServiceCollection();
  //当从容器获取ICalculate实例时,创建一个Calculate对象实例
        services.AddSingleton<ICalculate,Calculate>();
        //从容器获取一个Person类型的实例
        services.AddSingleton (typeof(Person));

        //通过ServiceCollection获取ServiceProvider
        ServiceProvider serviceProvider =  services.BuildServiceProvider ();

        //获取ICalculate类型的对象,创建对象,
        //相当于 ICalculate cal1 = new Calculate();
        ICalculate? cal1  = serviceProvider.GetService<ICalculate>();
        ICalculate? cal2  = serviceProvider.GetService<ICalculate>();

        //相当于 Person person1 = new Person();
        Person person1 = (Person)serviceProvider.GetService(typeof(Person));
        Person person2 = (Person)serviceProvider.GetService(typeof(Person));

        //true
        bool a1 = object.ReferenceEquals(person1,person2);

        //true
        bool aaa =  object.ReferenceEquals(cal1, cal2);
    }

 

posted @ 2022-08-24 22:19  薛定谔的小灯泡  阅读(154)  评论(0编辑  收藏  举报