1 概要说明 

1.1  AddSingleton<IA, A>();//创建单实例对象
1.2  AddTransient<IB, B>();//创建临时对象

2 应用举例

2.1 例1

2.1.1 代码

using System;
using Microsoft.Extensions.DependencyInjection;
 
namespace 依赖注入的生命周期
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            ServiceProvider RegisterServices()
            {
                IServiceCollection services = new ServiceCollection();
                services.AddSingleton<IA, A>();
                services.AddTransient<IB, B>();
                return services.BuildServiceProvider();
            }
            using (ServiceProvider container = RegisterServices())
            {
                Console.WriteLine($"requesting {nameof(ControllerX)}");
                IA a = container.GetRequiredService<IA>();
                IA a2 = container.GetRequiredService<IA>();
                IB b = container.GetRequiredService<IB>();
                IB b2 = container.GetRequiredService<IB>();
            }
 
            Console.ReadLine();
        }
    }
    interface IA
    {
        void fun();
    }
    interface IB
    {
        void fun();
    }
    public class A: IA
    {
        static int createNo = 0;
        public A()
        {
            createNo++;
            Console.WriteLine("A构造:" + createNo);
        }
    }
    public class B: IB
    {
        static int createNo = 0;
        public B()
        {
            createNo++;
            Console.WriteLine("B构造:" + createNo);
        }
    }
}
View Code

 

相关文章:

  • 2021-11-27
  • 2021-12-02
  • 2021-06-18
  • 2021-09-03
  • 2022-12-23
  • 2021-11-19
  • 2022-12-23
  • 2021-11-24
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2022-02-22
  • 2023-01-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案