ServiceDescriptor 类

位于 Microsoft.Extensions.DependencyInjection.Abstractions.dll

官方定义: 描述一种服务,包括该服务的类型,实现和生存周期 

// 生命周期
public ServiceLifetime Lifetime { get; }
// 服务类型
public Type ServiceType { get; }
// 实现类型 [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
public Type? ImplementationType { get; }
// 实例
public object? ImplementationInstance { get; }
// 服务提供者
public Func<IServiceProvider, object>? ImplementationFactory { get; }

重要的方法为 Describe 方法,直接返回一个 ServiceDescriptor  ,具有以下重载

private static ServiceDescriptor Describe<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(ServiceLifetime lifetime) where TService : class where TImplementation : class, TService
    {
        return Describe(typeof(TService), typeof(TImplementation), lifetime);
    }

    public static ServiceDescriptor Describe(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
    {
        return new ServiceDescriptor(serviceType, implementationType, lifetime);
    }

    public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
    {
        return new ServiceDescriptor(serviceType, implementationFactory, lifetime);
    }

其他方法都是直接调用 Describe 方法

// 生命周期为 ServiceLifetime.Transient
public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
    {
        return ServiceDescriptor.Describe<TService, TImplementation>(ServiceLifetime.Transient);
    }
// 生命周期为 ServiceLifetime.Scoped
public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
    {
        return ServiceDescriptor.Describe<TService, TImplementation>(ServiceLifetime.Scoped);
    }
// 生命周期为 ServiceLifetime.Singleton
public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
    {
        return ServiceDescriptor.Describe<TService, TImplementation>(ServiceLifetime.Singleton);
    }

 

posted @ 2022-11-18 17:05  顾小凡  阅读(142)  评论(0)    收藏  举报