asp.net core 依赖注入实现全过程粗略剖析(1)
转载请注明出处: https://home.cnblogs.com/u/zhiyong-ITNote/
常用扩展方法 注入依赖服务:
new ServiceCollection().AddSingleton<IApplicationBuilder, ApplicationBuilder>();
// AddSingleton多个重载方法 源码
public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService { if (services == null) { throw new ArgumentNullException(nameof(services)); } return services.AddSingleton(typeof(TService), typeof(TImplementation)); } // Singleton模式 最终的调用 public static IServiceCollection AddSingleton( 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.Singleton); } // 所有的Addxxx 最终都是调用Add方法,将ServiceDescriptor添加到IServiceCollection中: private static IServiceCollection Add( IServiceCollection collection, Type serviceType, Type implementationType, ServiceLifetime lifetime) { var descriptor = new ServiceDescriptor(serviceType, implementationType, lifetime); collection.Add(descriptor); return collection; } // IServiceCollection源码: public interface IServiceCollection : IList<ServiceDescriptor> {}