无名 发表于 2022-5-8 17:32:21

【L·S】浅谈.Net Core Dependency 二

其实IServiceCollection本质就是IList,而且并没有发现AddScoped、AddTransient、AddSingleton踪影,说明这几个方法是扩展方法,我们找到ServiceCollectionServiceExtensions扩展类的位置,我们平时用的方法都在这里,由于代码非常多这里就不全部粘贴出来了,我们只粘贴AddTransient相关的,AddScoped、AddSingleton的实现同理Copy/// /// 通过泛型注册/// public static IServiceCollection AddTransient(this IServiceCollection services)    where TService : class    where TImplementation : class, TService{    if (services == null)    {      throw new ArgumentNullException(nameof(services));    }    //得到泛型类型    return services.AddTransient(typeof(TService), typeof(TImplementation));}/// /// 根据类型注册/// public static IServiceCollection AddTransient(    this IServiceCollection services,    Type serviceType,    Type implementationType){    if (services == null)    {      throw new ArgumentNullException(nameof(services));    }    if (serviceType == null)    {      throw new ArgumentNullException(nameof(serviceType));    }    if (implementationType == null)    {      throw new ArgumentNullException(nameof(implementationType));    }    return Add(services, serviceType, implementationType, ServiceLifetime.Transient);}/// /// 根据类型实例来自工厂注册方法/// public static IServiceCollection AddTransient(    this IServiceCollection services,    Type serviceType,    Func implementationFactory){    if (services == null)    {      throw new ArgumentNullException(nameof(services));    }    if (serviceType == null)    {      throw new ArgumentNullException(nameof(serviceType));    }    if (implementationFactory == null)    {      throw new ArgumentNullException(nameof(implementationFactory));    }    return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient);}通过以上代码我们可以得到两个结论,一是注册服务的方法本质都是在调用Add重载的两个方法,二是声明周期最终还是通过ServiceLifetime来控制的AddScoped、AddTransient、AddSingleton只是分文别类的进行封装而已,我们来看ServiceLifetime的源码实现
http://cdn.u1.huluxia.com/g4/M03/A8/67/rBAAdl8HscqAU4QWAAKqv8KiwVM421.jpg
页: [1]
查看完整版本: 【L·S】浅谈.Net Core Dependency 二