无名商城论坛

搜索
查看: 232|回复: 0

[其他技术] 【L·S】浅谈.Net Core Dependency 二

[复制链接]

1万

主题

1万

帖子

3万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
32464
发表于 2022-5-8 17:32:21 | 显示全部楼层 |阅读模式
其实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的源码实现
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表