前段时间看了蒋老师的Core文章,对于DI那一块感觉挺有意思,然后就看了一下Core官方DI的源码,这也算是第一个看得懂大部分源码的框架,虽然官方DI相对来说特别简单,
官方DI相对于其它框架(例如 autofac)使用起来麻烦许多,既没有一次注入程序集中所有类的功能,也没有方便的属性注入,所以感觉起来官方的DI框架只是一个简单的标准,🔔属性注入:一种被称为
service Locator的模式,蒋老师在Core文章中也推荐了建议不要使用这种模式
首先从`ServiceDescriptor`和`ServiceCollection`来认识,这两个类也是注册时使用的类ServiceDescriptor,ServiceCollection
这两个类是我们使用注册服务的两个类型,注册服务时,DI都会封装成一个`ServiceDescriptor`类型进行缓存到`ServiceCollection`类型中,其中`ServiceCollection`有三个扩展类型ServiceCollectionServiceExtensions : 实现了各种我们所使用了注册方式
ServiceCollectionDescriptorExtensions 实现了各种TryAdd和删除替换等操作
ServiceCollectionContainerBuilderExtensions 实现了构造
ServiceProvider实例
ServiceCollection
使用官方DI时注册我们都是将服务注册到一个`ServiceCollection`对象中,`ServiceCollection`类型看名称感觉就是一个服务集合的类型,其实并没有错,`IServiceCollection`集合就是一个继承`IList<ServiceDescriptor>`集合接口的一个类型,而`ServiceDescriptor`类型则是一个注册的服务描述类型,我们传入注册最后都会封装为一个`ServiceDescriptor`类型然后缓存到`ServiceCollection`集合之中调用ServiceCollection实例对象的方法进行注册
static void Main(string[] args) { // 使用ServiceCollaction对象的扩展方法进行注册服务 IServiceCollection services = new ServiceCollection() // 提供具体实例类 .AddScoped<IFoo, Foo>() // 提供实例化具体的工厂 .AddScoped(typeof(IBar), _ => new Bar()) // 提供具体实例化对象,此方法只适用于Singleton生命周期 .AddSingleton(typeof(IBaz),new Baz()); }**IServiceCollection类型的继承关系** /// <summary> /// Specifies the contract for a collection of service descriptors. /// </summary> public interface IServiceCollection : IList<ServiceDescriptor>{}`ServiceCollection`本身类型中只有一些IList<T>具体实现方法,而所有注册的方法都是以扩展方法提供在一个
