Example #1
0
        private static void SingletonAndTransient()
        {
            Console.WriteLine(nameof(SingletonAndTransient));

            ServiceProvider RegisterServices()
            {
                IServiceCollection services = new ServiceCollection();

                services.AddSingleton <IServiceA, ServiceA>();
                services.AddTransient <IServiceB, ServiceB>();
                // services.AddSingleton<ControllerX>();
                services.Add(new ServiceDescriptor(typeof(ControllerX), typeof(ControllerX), ServiceLifetime.Transient));
                services.AddSingleton <INumberService, NumberService>();
                return(services.BuildServiceProvider());
            }

            using (ServiceProvider container = RegisterServices())
            {
                Console.WriteLine($"requesting {nameof(ControllerX)}");

                ControllerX x = container.GetRequiredService <ControllerX>();
                x.M();
                x.M();

                Console.WriteLine($"requesting {nameof(ControllerX)}");

                ControllerX x2 = container.GetRequiredService <ControllerX>();
                x2.M();

                Console.WriteLine();
            }
        }
Example #2
0
        private static void SingletonAndTransient()
        {
            Console.WriteLine(nameof(SingletonAndTransient));

            //局部方法,注册服务A,服务B,NumberService和控制器类ContorllerX
            ServiceProvider RegisterServices()
            {
                IServiceCollection services = new ServiceCollection();

                services.AddSingleton <IServiceA, ServiceA>(); //注册为临时服务
                services.AddTransient <IServiceB, ServiceB>(); //注册为单例服务
                // services.AddSingleton<ControllerX>();//单例服务
                //注册为临时服务
                services.Add(new ServiceDescriptor(typeof(ControllerX), typeof(ControllerX), ServiceLifetime.Transient));
                services.AddSingleton <INumberService, NumberService>();//注册为单例服务
                //创建容器服务器
                return(services.BuildServiceProvider());
            }

            //使用单例临时服务
            using (ServiceProvider container = RegisterServices())
            {
                //第一次请求创建ControllerX
                Console.WriteLine($"requesting {nameof(ControllerX)}");
                //创建ControllerX对象
                ControllerX x = container.GetRequiredService <ControllerX>();
                //连续调用2次M()
                x.M();
                x.M();

                //第二次请求创建ControllerX
                Console.WriteLine($"requesting {nameof(ControllerX)}");
                ControllerX x2 = container.GetRequiredService <ControllerX>();
                x2.M();

                Console.WriteLine();
            }
        }