翼度科技»论坛 编程开发 .net 查看内容

一个.NET内置依赖注入的小型强化版

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
前言

.NET生态中有许多依赖注入容器。在大多数情况下,微软提供的内置容器在易用性和性能方面都非常优秀。外加ASP.NET Core默认使用内置容器,使用很方便。
但是笔者在使用中一直有一个头疼的问题:服务工厂无法提供请求的服务类型相关的信息。这在一般情况下并没有影响,但是内置容器支持注册开放泛型服务,此时会导致无法实现某些需求。
ASP.NET Core目前推荐使用上下文池访问EF Core上下文,但是某些功能需要直接使用上下文(例如Identity Core)。官方文档建议使用自定义工厂通过上下文池获取上下文。这其实是一种服务转发(或委托),可以确保服务实例只有一个最终提供点,简化管理。
但是当希望转发的服务是开放泛型时就会出现问题。在实际请求服务时,无法通过自定义工厂得知请求的泛型服务的实际类型参数,也就无法实现对开放泛型类型的转发。官方仓库也有一个相关Issue:Dependency Injection of Open Generics via factory #41050。然而几年过去后微软依然没有打算解决这个问题。键控服务这种完全新增的功能都做了,这个举手之劳确一直放着,我不理解。一番研究后笔者确定可以通过简单的改造来实现支持,因此有了本篇文章。
新书宣传

有关新书的更多介绍欢迎查看《C#与.NET6 开发从入门到实践》上市,作者亲自来打广告了!

正文

本来笔者打算使用继承来扩展功能,但是几经周折后发现微软把关键类型设置为内部类和密封类,彻底断了这条路。无奈只能克隆仓库直接改代码,好死不死这个库是运行时仓库的一部分,完整仓库包含大量无关代码,直接fork也会带来一堆麻烦,最后只能克隆仓库后复制需要的部分来修改。
CoreDX.Extensions.DependencyInjection.Abstractions

这是基础抽象包,用于扩展ServiceDescriptor为后续改造提供基础支持。
TypedImplementationFactoryServiceDescriptor

要实现能从自定义工厂获取服务类型的功能,自定义工厂需要一个Type类型的参数来传递类型信息,那么就需要ServiceDescriptor提供相应的构造方法重载。原始类型显然不可能,好在这是个普通公共类,可以继承,因此笔者继承内置类并扩展了相应的成员来承载工厂委托。
  1. /// <inheritdoc />
  2. [DebuggerDisplay("{DebuggerToString(),nq}")]
  3. public class TypedImplementationFactoryServiceDescriptor : ServiceDescriptor
  4. {
  5.     private object? _typedImplementationFactory;
  6.     /// <summary>
  7.     /// Gets the typed factory used for creating service instances.
  8.     /// </summary>
  9.     public Func<IServiceProvider, Type, object>? TypedImplementationFactory
  10.     {
  11.         get
  12.         {
  13.             if (IsKeyedService)
  14.             {
  15.                 throw new InvalidOperationException("This service descriptor is keyed. Your service provider may not support keyed services.");
  16.             }
  17.             return (Func<IServiceProvider, Type, object>?)_typedImplementationFactory;
  18.         }
  19.     }
  20.     private object? _typedKeyedImplementationFactory;
  21.     /// <summary>
  22.     /// Gets the typed keyed factory used for creating service instances.
  23.     /// </summary>
  24.     public Func<IServiceProvider, object?, Type, object>? TypedKeyedImplementationFactory
  25.     {
  26.         get
  27.         {
  28.             if (!IsKeyedService)
  29.             {
  30.                 throw new InvalidOperationException("This service descriptor is not keyed.");
  31.             }
  32.             return (Func<IServiceProvider, object?, Type, object>?)_typedKeyedImplementationFactory;
  33.         }
  34.     }
  35.     /// <summary>
  36.     /// Don't use this!
  37.     /// </summary>
  38.     /// <inheritdoc />
  39.     public TypedImplementationFactoryServiceDescriptor(
  40.         Type serviceType,
  41.         object instance)
  42.         : base(serviceType, instance)
  43.     {
  44.         ThrowCtor();
  45.     }
  46.     /// <summary>
  47.     /// Don't use this!
  48.     /// </summary>
  49.     /// <inheritdoc />
  50.     public TypedImplementationFactoryServiceDescriptor(
  51.         Type serviceType,
  52.         [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType,
  53.         ServiceLifetime lifetime)
  54.         : base(serviceType, implementationType, lifetime)
  55.     {
  56.         ThrowCtor();
  57.     }
  58.     /// <summary>
  59.     /// Don't use this!
  60.     /// </summary>
  61.     /// <inheritdoc />
  62.     public TypedImplementationFactoryServiceDescriptor(
  63.         Type serviceType,
  64.         object? serviceKey,
  65.         object instance)
  66.         : base(serviceType, serviceKey, instance)
  67.     {
  68.         ThrowCtor();
  69.     }
  70.     /// <summary>
  71.     /// Don't use this!
  72.     /// </summary>
  73.     /// <inheritdoc />
  74.     public TypedImplementationFactoryServiceDescriptor(
  75.         Type serviceType,
  76.         Func<IServiceProvider, object> factory,
  77.         ServiceLifetime lifetime)
  78.         : base(serviceType, factory, lifetime)
  79.     {
  80.         ThrowCtor();
  81.     }
  82.     /// <summary>
  83.     /// Don't use this!
  84.     /// </summary>
  85.     /// <inheritdoc />
  86.     public TypedImplementationFactoryServiceDescriptor(
  87.         Type serviceType,
  88.         object? serviceKey,
  89.         [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType,
  90.         ServiceLifetime lifetime)
  91.         : base(serviceType, serviceKey, implementationType, lifetime)
  92.     {
  93.         ThrowCtor();
  94.     }
  95.     /// <summary>
  96.     /// Don't use this!
  97.     /// </summary>
  98.     /// <inheritdoc />
  99.     public TypedImplementationFactoryServiceDescriptor(
  100.         Type serviceType,
  101.         object? serviceKey,
  102.         Func<IServiceProvider, object?, object> factory,
  103.         ServiceLifetime lifetime)
  104.         : base(serviceType, serviceKey, factory, lifetime)
  105.     {
  106.         ThrowCtor();
  107.     }
  108.     /// <summary>
  109.     /// Initializes a new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/> with the specified factory.
  110.     /// </summary>
  111.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  112.     /// <param name="factory">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  113.     /// <param name="lifetime">The <see cref="ServiceLifetime"/> of the service.</param>
  114.     /// <exception cref="ArgumentNullException"></exception>
  115.     /// <inheritdoc />
  116.     public TypedImplementationFactoryServiceDescriptor(
  117.         Type serviceType,
  118.         Func<IServiceProvider, Type, object> factory,
  119.         ServiceLifetime lifetime)
  120.         : base(serviceType, ThrowFactory, lifetime)
  121.     {
  122.         CheckOpenGeneric(serviceType);
  123.         _typedImplementationFactory = factory ?? throw new ArgumentNullException(nameof(factory));
  124.     }
  125.     /// <summary>
  126.     /// Initializes a new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/> with the specified factory.
  127.     /// </summary>
  128.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  129.     /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  130.     /// <param name="factory">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  131.     /// <param name="lifetime">The <see cref="ServiceLifetime"/> of the service.</param>
  132.     /// <exception cref="ArgumentNullException"></exception>
  133.     /// <inheritdoc />
  134.     public TypedImplementationFactoryServiceDescriptor(
  135.         Type serviceType,
  136.         object? serviceKey,
  137.         Func<IServiceProvider, object?, Type, object> factory,
  138.         ServiceLifetime lifetime)
  139.         : base(serviceType, serviceKey, ThrowKeyedFactory, lifetime)
  140.     {
  141.         CheckOpenGeneric(serviceType);
  142.         _typedKeyedImplementationFactory = factory ?? throw new ArgumentNullException(nameof(factory));
  143.     }
  144.     /// <summary>
  145.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  146.     /// with the specified service in <paramref name="implementationFactory"/> and the <see cref="ServiceLifetime.Singleton"/> lifetime.
  147.     /// </summary>
  148.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  149.     /// <param name="implementationFactory">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  150.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  151.     public static TypedImplementationFactoryServiceDescriptor Singleton(
  152.         Type serviceType,
  153.         Func<IServiceProvider, Type, object> implementationFactory)
  154.     {
  155.         return new(serviceType, implementationFactory, ServiceLifetime.Singleton);
  156.     }
  157.     /// <summary>
  158.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  159.     /// with the specified service in <paramref name="implementationFactory"/> and the <see cref="ServiceLifetime.Singleton"/> lifetime.
  160.     /// </summary>
  161.     /// <typeparam name="TService">The type of the service.</typeparam>
  162.     /// <param name="implementationFactory">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  163.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  164.     public static TypedImplementationFactoryServiceDescriptor Singleton<TService>(
  165.         Func<IServiceProvider, Type, object> implementationFactory)
  166.         where TService : class
  167.     {
  168.         return new(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
  169.     }
  170.     /// <summary>
  171.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  172.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Singleton"/> lifetime.
  173.     /// </summary>
  174.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  175.     /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  176.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  177.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  178.     public static TypedImplementationFactoryServiceDescriptor KeyedSingleton(
  179.         Type serviceType,
  180.         object? serviceKey,
  181.         Func<IServiceProvider, object?, Type, object> implementationType)
  182.     {
  183.         return new(serviceType, serviceKey, implementationType, ServiceLifetime.Singleton);
  184.     }
  185.     /// <summary>
  186.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  187.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Singleton"/> lifetime.
  188.     /// </summary>
  189.     /// <typeparam name="TService">The type of the service.</typeparam>
  190.     /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  191.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  192.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  193.     public static TypedImplementationFactoryServiceDescriptor KeyedSingleton<TService>(
  194.         object? serviceKey,
  195.         Func<IServiceProvider, object?, Type, object> implementationType)
  196.         where TService : class
  197.     {
  198.         return new(typeof(TService), serviceKey, implementationType, ServiceLifetime.Singleton);
  199.     }
  200.     /// <summary>
  201.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  202.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Scoped"/> lifetime.
  203.     /// </summary>
  204.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  205.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  206.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  207.     public static TypedImplementationFactoryServiceDescriptor Scoped(
  208.         Type serviceType,
  209.         Func<IServiceProvider, Type, object> implementationType)
  210.     {
  211.         return new(serviceType, implementationType, ServiceLifetime.Scoped);
  212.     }
  213.     /// <summary>
  214.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  215.     /// with the specified service in <paramref name="implementationFactory"/> and the <see cref="ServiceLifetime.Scoped"/> lifetime.
  216.     /// </summary>
  217.     /// <typeparam name="TService">The type of the service.</typeparam>
  218.     /// <param name="implementationFactory">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  219.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  220.     public static TypedImplementationFactoryServiceDescriptor Scoped<TService>(
  221.         Func<IServiceProvider, Type, object> implementationFactory)
  222.         where TService : class
  223.     {
  224.         return new(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
  225.     }
  226.     /// <summary>
  227.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  228.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Scoped"/> lifetime.
  229.     /// </summary>
  230.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  231.     /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  232.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  233.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  234.     public static TypedImplementationFactoryServiceDescriptor KeyedScoped(
  235.         Type serviceType,
  236.         object? serviceKey,
  237.         Func<IServiceProvider, object?, Type, object> implementationType)
  238.     {
  239.         return new(serviceType, serviceKey, implementationType, ServiceLifetime.Scoped);
  240.     }
  241.     /// <summary>
  242.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  243.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Scoped"/> lifetime.
  244.     /// </summary>
  245.     /// <typeparam name="TService">The type of the service.</typeparam>
  246.     /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  247.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  248.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  249.     public static TypedImplementationFactoryServiceDescriptor KeyedScoped<TService>(
  250.         object? serviceKey,
  251.         Func<IServiceProvider, object?, Type, object> implementationType)
  252.         where TService : class
  253.     {
  254.         return new(typeof(TService), serviceKey, implementationType, ServiceLifetime.Scoped);
  255.     }
  256.     /// <summary>
  257.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  258.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Transient"/> lifetime.
  259.     /// </summary>
  260.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  261.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  262.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  263.     public static TypedImplementationFactoryServiceDescriptor Transient(
  264.         Type serviceType,
  265.         Func<IServiceProvider, Type, object> implementationType)
  266.     {
  267.         return new(serviceType, implementationType, ServiceLifetime.Transient);
  268.     }
  269.     /// <summary>
  270.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  271.     /// with the specified service in <paramref name="implementationFactory"/> and the <see cref="ServiceLifetime.Transient"/> lifetime.
  272.     /// </summary>
  273.     /// <typeparam name="TService">The type of the service.</typeparam>
  274.     /// <param name="implementationFactory">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  275.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  276.     public static TypedImplementationFactoryServiceDescriptor Transient<TService>(
  277.         Func<IServiceProvider, Type, object> implementationFactory)
  278.         where TService : class
  279.     {
  280.         return new(typeof(TService), implementationFactory, ServiceLifetime.Transient);
  281.     }
  282.     /// <summary>
  283.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  284.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Transient"/> lifetime.
  285.     /// </summary>
  286.     /// <param name="serviceType">The <see cref="Type"/> of the service.</param>
  287.     /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  288.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  289.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  290.     public static TypedImplementationFactoryServiceDescriptor KeyedTransient(
  291.         Type serviceType,
  292.         object? serviceKey,
  293.         Func<IServiceProvider, object?, Type, object> implementationType)
  294.     {
  295.         return new(serviceType, serviceKey, implementationType, ServiceLifetime.Transient);
  296.     }
  297.     /// <summary>
  298.     /// Creates an instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>
  299.     /// with the specified service in <paramref name="implementationType"/> and the <see cref="ServiceLifetime.Transient"/> lifetime.
  300.     /// </summary>
  301.     /// <typeparam name="TService">The type of the service.</typeparam>
  302.     /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  303.     /// <param name="implementationType">A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.</param>
  304.     /// <returns>A new instance of <see cref="TypedImplementationFactoryServiceDescriptor"/>.</returns>
  305.     public static TypedImplementationFactoryServiceDescriptor KeyedTransient<TService>(
  306.         object? serviceKey,
  307.         Func<IServiceProvider, object?, Type, object> implementationType)
  308.         where TService : class
  309.     {
  310.         return new(typeof(TService), serviceKey, implementationType, ServiceLifetime.Transient);
  311.     }
  312.     private string DebuggerToString()
  313.     {
  314.         string text = $"Lifetime = {Lifetime}, ServiceType = "{ServiceType.FullName}"";
  315.         if (IsKeyedService)
  316.         {
  317.             text += $", ServiceKey = "{ServiceKey}"";
  318.             return text + $", TypedKeyedImplementationFactory = {TypedKeyedImplementationFactory!.Method}";
  319.         }
  320.         else
  321.         {
  322.             return text + $", TypedImplementationFactory = {TypedImplementationFactory!.Method}";
  323.         }
  324.     }
  325.     private static void ThrowCtor()
  326.     {
  327.         throw new NotSupportedException($"{nameof(TypedImplementationFactoryServiceDescriptor)} only use for typed factory.");
  328.     }
  329.     private static object ThrowFactory(IServiceProvider serviceProvider)
  330.     {
  331.         throw new InvalidOperationException("Please use typed factory instead.");
  332.     }
  333.     private static object ThrowKeyedFactory(IServiceProvider serviceProvider, object? serviceKey)
  334.     {
  335.         throw new InvalidOperationException("Please use typed keyed factory instead.");
  336.     }
  337.     private static void CheckOpenGeneric(Type serviceType)
  338.     {
  339.         if (!serviceType.IsGenericTypeDefinition)
  340.             throw new InvalidOperationException($"{nameof(TypedImplementationFactoryServiceDescriptor)} only used for generic type definition(open generic type).");
  341.     }
  342. }
复制代码
这个类很简单,就是增加了用于保存Func和Func工厂委托的字段和配套的构造方法和验证逻辑。基类提供的所有功能均直接抛出异常,专门负责新增功能。
ImplementationFactoryServiceTypeHolder
  1. internal sealed class ImplementationFactoryServiceTypeHolder(Type serviceType)
  2. {
  3.     private readonly Func<IServiceProvider, object?> _factory = sp => sp.GetService(serviceType);
  4.     public Func<IServiceProvider, object?> Factory => _factory;
  5. }
  6. internal sealed class KeyedImplementationFactoryServiceTypeHolder(Type serviceType)
  7. {
  8.     private readonly Func<IServiceProvider, object?, object?> _factory = (sp, key) => (sp as IKeyedServiceProvider)?.GetKeyedService(serviceType, key);
  9.     public Func<IServiceProvider, object?, object?> Factory => _factory;
  10. }
  11. internal sealed class OpenGenericImplementationFactoryServiceTypeHolder(Type serviceType)
  12. {
  13.     private readonly Func<IServiceProvider, Type, object?> _factory = serviceType.IsGenericTypeDefinition
  14.         ? (sp, type) =>
  15.         {
  16.             var closed = serviceType.MakeGenericType(type.GenericTypeArguments);
  17.             return sp.GetService(closed);
  18.         }
  19.         : throw new ArgumentException($"{nameof(serviceType)} is not generic type definition.");
  20.     public Func<IServiceProvider, Type, object?> Factory => _factory;
  21. }
  22. internal sealed class KeyedOpenGenericImplementationFactoryServiceTypeHolder(Type serviceType)
  23. {
  24.     private readonly Func<IServiceProvider, object?, Type, object?> _factory = serviceType.IsGenericTypeDefinition
  25.         ? (sp, key, type) =>
  26.         {
  27.             var closed = serviceType.MakeGenericType(type.GenericTypeArguments);
  28.             return (sp as IKeyedServiceProvider)?.GetKeyedService(closed, key);
  29.         }
  30.         : throw new ArgumentException($"{nameof(serviceType)} is not generic type definition.");
  31.     public Func<IServiceProvider, object?, Type, object?> Factory => _factory;
  32. }
复制代码
这个类也很简单,只负责持有服务类型,并把新的工厂类型转换到原始工厂类型方便集成进内置容器。并且这是内部辅助类型,对开发者是无感知的。
易用性扩展

最后就是提供扩展方法提供和内置容器相似的使用体验。由于本次扩展的主要目的是实现开放发型的服务转发,因此笔者专门准备了一套用来注册服务转发的AddForward系列扩展方便使用。此处只列出部分预览。
  1. /// <summary>
  2. /// Adds a service of the type specified in <paramref name="serviceType"/> with a factory
  3. /// specified in <paramref name="implementationFactory"/> to the specified <see cref="IServiceCollection"/>.
  4. /// </summary>
  5. /// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
  6. /// <param name="serviceType">The type of the service to register.</param>
  7. /// <param name="implementationFactory">The factory that creates the service.</param>
  8. /// <param name="serviceLifetime">The <see cref="ServiceLifetime"/> of <paramref name="serviceType"/>.</param>
  9. /// <returns>A reference to this instance after the operation has completed.</returns>
  10. public static IServiceCollection AddTypedFactory(
  11.     this IServiceCollection services,
  12.     Type serviceType,
  13.     Func<IServiceProvider, Type, object> implementationFactory,
  14.     ServiceLifetime serviceLifetime)
  15. {
  16.     services.Add(new TypedImplementationFactoryServiceDescriptor(serviceType, implementationFactory, serviceLifetime));
  17.     return services;
  18. }
  19. /// <summary>
  20. /// Adds a service of the type specified in <paramref name="serviceType"/> with a factory
  21. /// specified in <paramref name="implementationFactory"/> to the specified <see cref="IServiceCollection"/>.
  22. /// </summary>
  23. /// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
  24. /// <param name="serviceType">The type of the service to register.</param>
  25. /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  26. /// <param name="implementationFactory">The factory that creates the service.</param>
  27. /// <param name="serviceLifetime">The <see cref="ServiceLifetime"/> of <paramref name="serviceType"/>.</param>
  28. /// <returns>A reference to this instance after the operation has completed.</returns>
  29. public static IServiceCollection AddKeyedTypedFactory(
  30.     this IServiceCollection services,
  31.     Type serviceType,
  32.     object? serviceKey,
  33.     Func<IServiceProvider, object?, Type, object> implementationFactory,
  34.     ServiceLifetime serviceLifetime)
  35. {
  36.     services.Add(new TypedImplementationFactoryServiceDescriptor(serviceType, serviceKey, implementationFactory, serviceLifetime));
  37.     return services;
  38. }
  39. /// <summary>
  40. /// Adds a service of the type specified in <paramref name="serviceType"/> with a forward of the type
  41. /// specified in <paramref name="forwardTargetServiceType"/> to the specified <see cref="IServiceCollection"/>.
  42. /// </summary>
  43. /// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
  44. /// <param name="serviceType">The type of the service to register.</param>
  45. /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  46. /// <param name="forwardTargetServiceType">The forward type of the service.</param>
  47. /// <param name="serviceLifetime">The <see cref="ServiceLifetime"/> of <paramref name="serviceType"/>.</param>
  48. /// <returns>A reference to this instance after the operation has completed.</returns>
  49. public static IServiceCollection AddKeyedForward(
  50.     this IServiceCollection services,
  51.     Type serviceType,
  52.     object? serviceKey,
  53.     Type forwardTargetServiceType,
  54.     ServiceLifetime serviceLifetime)
  55. {
  56.     ArgumentNullException.ThrowIfNull(services);
  57.     ArgumentNullException.ThrowIfNull(serviceType);
  58.     ArgumentNullException.ThrowIfNull(forwardTargetServiceType);
  59.     if (serviceType.IsGenericTypeDefinition)
  60.     {
  61.         services.Add(new TypedImplementationFactoryServiceDescriptor(serviceType, serviceKey, new KeyedOpenGenericImplementationFactoryServiceTypeHolder(forwardTargetServiceType).Factory!, serviceLifetime));
  62.     }
  63.     else
  64.     {
  65.         services.Add(new ServiceDescriptor(serviceType, serviceKey, new KeyedImplementationFactoryServiceTypeHolder(forwardTargetServiceType).Factory!, serviceLifetime));
  66.     }
  67.     return services;
  68. }
复制代码
从示例可以发现如果类型不是开放泛型,是直接使用原始类型进行注册的。也就是说如果安装这个抽象包,但是不使用开放泛型的相关功能,是可以直接用原始内置容器的。
CoreDX.Extensions.DependencyInjection

这是修改后的服务容器实现,增加了对带服务类型的自定义工厂的支持,其他内置功能完全不变。
CallSiteFactory
  1. internal sealed partial class CallSiteFactory : IServiceProviderIsService, IServiceProviderIsKeyedService
  2. {
  3.     // 其他原始代码
  4.     private void Populate()
  5.     {
  6.         foreach (ServiceDescriptor descriptor in _descriptors)
  7.         {
  8.             Type serviceType = descriptor.ServiceType;
  9.             #region 验证可识别请求类型的服务实现工厂
  10.             if (descriptor is TypedImplementationFactoryServiceDescriptor typedFactoryDescriptor)
  11.             {
  12.                 if(typedFactoryDescriptor.IsKeyedService && typedFactoryDescriptor.TypedKeyedImplementationFactory == null)
  13.                 {
  14.                     throw new ArgumentException(
  15.                         $"Keyed open generic service {serviceType} requires {nameof(typedFactoryDescriptor.TypedKeyedImplementationFactory)}",
  16.                         "descriptors");
  17.                 }
  18.                 else if (!typedFactoryDescriptor.IsKeyedService && typedFactoryDescriptor.TypedImplementationFactory == null)
  19.                 {
  20.                     throw new ArgumentException(
  21.                         $"Open generic service {serviceType} requires {nameof(typedFactoryDescriptor.TypedImplementationFactory)}",
  22.                         "descriptors");
  23.                 }
  24.             }
  25.             #endregion
  26.             // 其他原始代码
  27.         }
  28.     }
  29.     private ServiceCallSite? TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, int slot)
  30.     {
  31.         if (serviceIdentifier.ServiceType == descriptor.ServiceType)
  32.         {
  33.             ServiceCacheKey callSiteKey = new ServiceCacheKey(serviceIdentifier, slot);
  34.             if (_callSiteCache.TryGetValue(callSiteKey, out ServiceCallSite? serviceCallSite))
  35.             {
  36.                 return serviceCallSite;
  37.             }
  38.             ServiceCallSite callSite;
  39.             var lifetime = new ResultCache(descriptor.Lifetime, serviceIdentifier, slot);
  40.             // 其他原始代码
  41.             #region 为可识别请求类型的服务工厂注册服务实现工厂
  42.             else if (TryCreateTypedFactoryCallSite(lifetime, descriptor as TypedImplementationFactoryServiceDescriptor, descriptor.ServiceType) is ServiceCallSite factoryCallSite)
  43.             {
  44.                 callSite = factoryCallSite;
  45.             }
  46.             #endregion
  47.             // 其他原始代码
  48.             return _callSiteCache[callSiteKey] = callSite;
  49.         }
  50.         return null;
  51.     }
  52.     [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:MakeGenericType",
  53.         Justification = "MakeGenericType here is used to create a closed generic implementation type given the closed service type. " +
  54.         "Trimming annotations on the generic types are verified when 'Microsoft.Extensions.DependencyInjection.VerifyOpenGenericServiceTrimmability' is set, which is set by default when PublishTrimmed=true. " +
  55.         "That check informs developers when these generic types don't have compatible trimming annotations.")]
  56.     [UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode",
  57.         Justification = "When ServiceProvider.VerifyAotCompatibility is true, which it is by default when PublishAot=true, " +
  58.         "this method ensures the generic types being created aren't using ValueTypes.")]
  59.     private ServiceCallSite? TryCreateOpenGeneric(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, int slot, bool throwOnConstraintViolation)
  60.     {
  61.         if (serviceIdentifier.IsConstructedGenericType &&
  62.             serviceIdentifier.ServiceType.GetGenericTypeDefinition() == descriptor.ServiceType)
  63.         {
  64.             ServiceCacheKey callSiteKey = new ServiceCacheKey(serviceIdentifier, slot);
  65.             if (_callSiteCache.TryGetValue(callSiteKey, out ServiceCallSite? serviceCallSite))
  66.             {
  67.                 return serviceCallSite;
  68.             }
  69.             Type? implementationType = descriptor.GetImplementationType();
  70.             //Debug.Assert(implementationType != null, "descriptor.ImplementationType != null"); // 延迟断言,此处可能是开放泛型工厂
  71.             var lifetime = new ResultCache(descriptor.Lifetime, serviceIdentifier, slot);
  72.             Type closedType;
  73.             try
  74.             {
  75.                 Type[] genericTypeArguments = serviceIdentifier.ServiceType.GenericTypeArguments;
  76.                 if (TypedImplementationFactoryServiceProvider.VerifyAotCompatibility)
  77.                 {
  78.                     VerifyOpenGenericAotCompatibility(serviceIdentifier.ServiceType, genericTypeArguments);
  79.                 }
  80.                 #region 为开放式泛型服务添加可识别请求类型的服务实现工厂
  81.                 if (descriptor is TypedImplementationFactoryServiceDescriptor typedFactoryDescriptor)
  82.                 {
  83.                     closedType = typedFactoryDescriptor.ServiceType.MakeGenericType(genericTypeArguments);
  84.                     if (TryCreateTypedFactoryCallSite(lifetime, typedFactoryDescriptor, closedType) is ServiceCallSite factoryCallSite)
  85.                     {
  86.                         return _callSiteCache[callSiteKey] = factoryCallSite;
  87.                     }
  88.                     else
  89.                     {
  90.                         return null;
  91.                     }
  92.                 }
  93.                 // 断言移动到此处
  94.                 Debug.Assert(implementationType != null, "descriptor.ImplementationType != null");
  95.                 #endregion
  96.                 closedType = implementationType.MakeGenericType(genericTypeArguments);
  97.             }
  98.             catch (ArgumentException)
  99.             {
  100.                 if (throwOnConstraintViolation)
  101.                 {
  102.                     throw;
  103.                 }
  104.                 return null;
  105.             }
  106.             return _callSiteCache[callSiteKey] = CreateConstructorCallSite(lifetime, serviceIdentifier, closedType, callSiteChain);
  107.         }
  108.         return null;
  109.     }
  110.     // 其他原始代码
  111. }
复制代码
这是整个改造的关键,理论上来说只要这个类是普通类的话完全可以直接通过继承把功能加上,可惜不是。此处只展示修改的部分。然后把辅助方法定义到另一个文件,方便利用部分类的特点尽量减少对原始代码的改动,方便将来同步官方代码。
  1. internal sealed partial class CallSiteFactory
  2. {
  3.         /// <summary>
  4.         /// 尝试创建可识别请求类型的工厂调用点
  5.         /// </summary>
  6.         /// <param name="lifetime"></param>
  7.         /// <param name="descriptor"></param>
  8.         /// <param name="serviceType">服务类型</param>
  9.         /// <returns></returns>
  10.         private static FactoryCallSite? TryCreateTypedFactoryCallSite(
  11.                 ResultCache lifetime,
  12.                 TypedImplementationFactoryServiceDescriptor? descriptor,
  13.                 Type serviceType)
  14.         {
  15.         ArgumentNullException.ThrowIfNull(serviceType);
  16.         if (descriptor == null) { }
  17.                 else if (descriptor.IsKeyedService && descriptor.TypedKeyedImplementationFactory != null)
  18.                 {
  19.                         return new FactoryCallSite(lifetime, descriptor.ServiceType, descriptor.ServiceKey!, new TypedKeyedServiceImplementationFactoryHolder(descriptor.TypedKeyedImplementationFactory!, serviceType).Factory);
  20.                 }
  21.                 else if (!descriptor.IsKeyedService && descriptor.TypedImplementationFactory != null)
  22.         {
  23.                         return new FactoryCallSite(lifetime, descriptor.ServiceType, new TypedServiceImplementationFactoryHolder(descriptor.TypedImplementationFactory!, serviceType).Factory);
  24.                 }
  25.         return null;
  26.         }
  27. }
复制代码
TypedServiceImplementationFactoryHolder
  1. internal sealed class TypedServiceImplementationFactoryHolder
  2. {
  3.     private readonly Func<IServiceProvider, Type, object> _factory;
  4.     private readonly Type _serviceType;
  5.     internal TypedServiceImplementationFactoryHolder(Func<IServiceProvider, Type, object> factory, Type serviceType)
  6.     {
  7.         _factory = factory ?? throw new ArgumentNullException(nameof(factory));
  8.         _serviceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType));
  9.     }
  10.     internal Func<IServiceProvider, object> Factory => FactoryFunc;
  11.     private object FactoryFunc(IServiceProvider provider)
  12.     {
  13.         return _factory(provider, _serviceType);
  14.     }
  15. }
  16. internal sealed class TypedKeyedServiceImplementationFactoryHolder
  17. {
  18.     private readonly Func<IServiceProvider, object?, Type, object> _factory;
  19.     private readonly Type _serviceType;
  20.     internal TypedKeyedServiceImplementationFactoryHolder(Func<IServiceProvider, object?, Type, object> factory, Type serviceType)
  21.     {
  22.         _factory = factory ?? throw new ArgumentNullException(nameof(factory));
  23.         _serviceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType));
  24.     }
  25.     internal Func<IServiceProvider, object?, object> Factory => FactoryFunc;
  26.     private object FactoryFunc(IServiceProvider provider, object? serviceKey)
  27.     {
  28.         return _factory(provider, serviceKey, _serviceType);
  29.     }
  30. }
复制代码
因为笔者直接使用了内置类型,因此需要把工厂委托转换成内置容器支持的签名。Holder辅助类就可以把类型信息保存为内部字段,对外暴露的工厂签名就可以不需要类型参数了。
最后为避免引起误解,笔者修改了类名,但保留文件名方便比对原始仓库代码。至此,改造其实已经完成。可以看出改动真的很少,不知道为什么微软就是不改。
CoreDX.Extensions.DependencyInjection.Hosting.Abstractions

虽然经过上面的改造后,改版容器已经能用了,但是为了方便和通用主机系统集成还是要提供一个替换容器用的扩展。
TypedImplementationFactoryHostingHostBuilderExtensions
  1. public static class TypedImplementationFactoryHostingHostBuilderExtensions
  2. {
  3.     /// <summary>
  4.     /// Specify the <see cref="IServiceProvider"/> to be the typed implementation factory supported one.
  5.     /// </summary>
  6.     /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to configure.</param>
  7.     /// <returns>The <see cref="IHostBuilder"/>.</returns>
  8.     public static IHostBuilder UseTypedImplementationFactoryServiceProvider(
  9.         this IHostBuilder hostBuilder)
  10.         => hostBuilder.UseTypedImplementationFactoryServiceProvider(static _ => { });
  11.     /// <summary>
  12.     /// Specify the <see cref="IServiceProvider"/> to be the typed implementation factory supported one.
  13.     /// </summary>
  14.     /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to configure.</param>
  15.     /// <param name="configure">The delegate that configures the <see cref="IServiceProvider"/>.</param>
  16.     /// <returns>The <see cref="IHostBuilder"/>.</returns>
  17.     public static IHostBuilder UseTypedImplementationFactoryServiceProvider(
  18.         this IHostBuilder hostBuilder,
  19.         Action<ServiceProviderOptions> configure)
  20.         => hostBuilder.UseTypedImplementationFactoryServiceProvider((context, options) => configure(options));
  21.     /// <summary>
  22.     /// Specify the <see cref="IServiceProvider"/> to be the typed implementation factory supported one.
  23.     /// </summary>
  24.     /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to configure.</param>
  25.     /// <param name="configure">The delegate that configures the <see cref="IServiceProvider"/>.</param>
  26.     /// <returns>The <see cref="IHostBuilder"/>.</returns>
  27.     public static IHostBuilder UseTypedImplementationFactoryServiceProvider(
  28.         this IHostBuilder hostBuilder,
  29.         Action<HostBuilderContext, ServiceProviderOptions> configure)
  30.     {
  31.         return hostBuilder.UseServiceProviderFactory(context =>
  32.         {
  33.             var options = new ServiceProviderOptions();
  34.             configure(context, options);
  35.             return new TypedImplementationFactoryServiceProviderFactory(options);
  36.         });
  37.     }
  38. }
复制代码
至此,主机集成工作也完成了。本来打算就这么结束的,结果突然想起来,开放泛型问题解决了,键控服务也有了,之前一直不知道怎么办的动态代理貌似是有戏了,就又研究起来了。
CoreDX.Extensions.DependencyInjection.Proxies.Abstractions

之前动态代理不好实现主要是因为代理服务和原始服务的注册类型相同,实在是没办法。既然现在有键控服务了,那么把原始服务和代理服务用键分开就完美搞定,最后一个问题就是键要怎么处理。通过文档可知键控服务的键可以是任意object,只要实现合理的相等性判断即可。因此笔者决定使用专用的类型来表示代理服务的键,并通过对string类型的特殊处理来实现特性键指定的兼容。
ImplicitProxyServiceOriginalServiceKey
  1. /// <summary>
  2. /// Service key for access original service that already added as implicit proxy.
  3. /// </summary>
  4. public sealed class ImplicitProxyServiceOriginalServiceKey
  5.     : IEquatable<ImplicitProxyServiceOriginalServiceKey>
  6. #if NET7_0_OR_GREATER
  7.     , IEqualityOperators<ImplicitProxyServiceOriginalServiceKey, ImplicitProxyServiceOriginalServiceKey, bool>
  8.     , IEqualityOperators<ImplicitProxyServiceOriginalServiceKey, object, bool>
  9. #endif
  10. {
  11.     private const int _hashCodeBase = 870983858;
  12.     private readonly bool _isStringMode;
  13.     private readonly object? _originalServiceKey;
  14.     private static readonly ImplicitProxyServiceOriginalServiceKey _default = CreateOriginalServiceKey(null);
  15.     private static readonly ImplicitProxyServiceOriginalServiceKey _stringDefault = CreateStringOriginalServiceKey(null);
  16.     /// <summary>
  17.     /// Prefix for access original <see cref="string"/> based keyed service that already added as implicit proxy.
  18.     /// </summary>
  19.     public const string DefaultStringPrefix = $"[{nameof(CoreDX)}.{nameof(Extensions)}.{nameof(DependencyInjection)}.{nameof(Proxies)}.{nameof(ImplicitProxyServiceOriginalServiceKey)}](ImplicitDefault)";
  20.     /// <summary>
  21.     /// Default original service key for none keyed proxy service.
  22.     /// </summary>
  23.     public static ImplicitProxyServiceOriginalServiceKey Default => _default;
  24.     /// <summary>
  25.     /// Default original service key for none <see cref="string"/> based keyed proxy service.
  26.     /// </summary>
  27.     public static ImplicitProxyServiceOriginalServiceKey StringDefault => _stringDefault;
  28.     /// <summary>
  29.     /// Service key of original service.
  30.     /// </summary>
  31.     public object? OriginalServiceKey => _originalServiceKey;
  32.     public bool Equals(ImplicitProxyServiceOriginalServiceKey? other)
  33.     {
  34.         return Equals((object?)other);
  35.     }
  36.     public override bool Equals(object? obj)
  37.     {
  38.         if (_isStringMode && obj is string str) return $"{DefaultStringPrefix}{_originalServiceKey}" == str;
  39.         else
  40.         {
  41.             var isEquals = obj is not null and ImplicitProxyServiceOriginalServiceKey other
  42.             && ((_originalServiceKey is null && other._originalServiceKey is null) || _originalServiceKey?.Equals(other._originalServiceKey) is true);
  43.             return isEquals;
  44.         }
  45.     }
  46.     public static bool operator ==(ImplicitProxyServiceOriginalServiceKey? left, ImplicitProxyServiceOriginalServiceKey? right)
  47.     {
  48.         return left?.Equals(right) is true;
  49.     }
  50.     public static bool operator !=(ImplicitProxyServiceOriginalServiceKey? left, ImplicitProxyServiceOriginalServiceKey? right)
  51.     {
  52.         return !(left == right);
  53.     }
  54.     public static bool operator ==(ImplicitProxyServiceOriginalServiceKey? left, object? right)
  55.     {
  56.         return left?.Equals(right) is true;
  57.     }
  58.     public static bool operator !=(ImplicitProxyServiceOriginalServiceKey? left, object? right)
  59.     {
  60.         return !(left == right);
  61.     }
  62.     public static bool operator ==(object? left, ImplicitProxyServiceOriginalServiceKey? right)
  63.     {
  64.         return right == left;
  65.     }
  66.     public static bool operator !=(object? left, ImplicitProxyServiceOriginalServiceKey? right)
  67.     {
  68.         return right != left;
  69.     }
  70.     public override int GetHashCode()
  71.     {
  72.         return _isStringMode
  73.             ? $"{DefaultStringPrefix}{_originalServiceKey}".GetHashCode()
  74.             : HashCode.Combine(_hashCodeBase, _originalServiceKey);
  75.     }
  76.     /// <summary>
  77.     /// Creates an instance of <see cref="ImplicitProxyServiceOriginalServiceKey"/> with the specified service key in <paramref name="originalServiceKey"/>.
  78.     /// </summary>
  79.     /// <param name="originalServiceKey"></param>
  80.     /// <returns>A new instance of <see cref="ImplicitProxyServiceOriginalServiceKey"/>.</returns>
  81.     public static ImplicitProxyServiceOriginalServiceKey CreateOriginalServiceKey(object? originalServiceKey)
  82.     {
  83.         return new(originalServiceKey, false);
  84.     }
  85.     /// <summary>
  86.     /// Creates an instance of <see cref="ImplicitProxyServiceOriginalServiceKey"/> with the specified <see cref="string"/> based service key in <paramref name="originalServiceKey"/>.
  87.     /// </summary>
  88.     /// <param name="originalServiceKey"></param>
  89.     /// <returns>A new instance of <see cref="ImplicitProxyServiceOriginalServiceKey"/>.</returns>
  90.     public static ImplicitProxyServiceOriginalServiceKey CreateStringOriginalServiceKey(string? originalServiceKey)
  91.     {
  92.         return new(originalServiceKey, true);
  93.     }
  94.     private ImplicitProxyServiceOriginalServiceKey(object? originalServiceKey, bool isStringMode)
  95.     {
  96.         _originalServiceKey = originalServiceKey;
  97.         _isStringMode = isStringMode;
  98.     }
  99. }
复制代码
对.NET 7以上版本,把运算符实现为接口。
ProxyService
  1. /// <summary>
  2. /// The interface for get explicit proxy service.
  3. /// </summary>
  4. /// <typeparam name="TService">The type of original service to get explicit proxy.</typeparam>
  5. public interface IProxyService<out TService>
  6.     where TService : class
  7. {
  8.     /// <summary>
  9.     /// Get proxy service instance of type <typeparamref name="TService"/>.
  10.     /// </summary>
  11.     TService Proxy { get; }
  12. }
  13. /// <summary>
  14. /// The type for get explicit proxy service.
  15. /// </summary>
  16. /// <typeparam name="TService">The type of original service to get explicit proxy.</typeparam>
  17. /// <param name="service">Object instance of original service to be proxy.</param>
  18. internal sealed class ProxyService<TService>(TService service) : IProxyService<TService>
  19.     where TService : class
  20. {
  21.     public TService Proxy { get; } = service;
  22. }
复制代码
除了隐式代理,笔者还准备了显式代理,这也是笔者要在内置容器上扩展而不是去用其他第三方容器的一个原因。第三方容器代理后原始服务就被隐藏了,在某些极端情况下万一要用到原始服务就没办法了。
CastleDynamicProxyDependencyInjectionExtensions

此处只展示部分预览。
  1. /// <summary>
  2. /// Adds a explicit proxy for the type specified in <paramref name="serviceType"/> with interceptors
  3. /// specified in <paramref name="interceptorTypes"/> to the specified <see cref="IServiceCollection"/>.
  4. /// </summary>
  5. /// <param name="services">The <see cref="IServiceCollection"/> to add the service proxy to.</param>
  6. /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  7. /// <param name="serviceType">The type of the service to add proxy.</param>
  8. /// <param name="serviceLifetime">The <see cref="ServiceLifetime"/> of <paramref name="serviceType"/> and <paramref name="interceptorTypes"/>.</param>
  9. /// <param name="interceptorTypes">The interceptor types of the service proxy.</param>
  10. /// <returns>A reference to this instance after the operation has completed.</returns>
  11. /// <remarks>Use <see cref="IProxyService{TService}"/> to get proxy service.</remarks>
  12. public static IServiceCollection AddKeyedExplicitProxy(
  13.     this IServiceCollection services,
  14.     Type serviceType,
  15.     object? serviceKey,
  16.     ServiceLifetime serviceLifetime,
  17.     params Type[] interceptorTypes)
  18. {
  19.     ArgumentNullException.ThrowIfNull(services);
  20.     ArgumentNullException.ThrowIfNull(serviceType);
  21.     CheckInterface(serviceType);
  22.     CheckInterceptor(interceptorTypes);
  23.     if (serviceType.IsGenericTypeDefinition)
  24.     {
  25.         services.TryAddKeyedSingleton<IStartupOpenGenericServiceProxyRegister>(serviceKey, new StartupOpenGenericServiceProxyRegister());
  26.         var startupOpenGenericServiceProxyRegister = services
  27.             .LastOrDefault(service => service.IsKeyedService && service.ServiceKey == serviceKey && service.ServiceType == typeof(IStartupOpenGenericServiceProxyRegister))
  28.             ?.KeyedImplementationInstance as IStartupOpenGenericServiceProxyRegister
  29.             ?? throw new InvalidOperationException($"Can not found keyed(key value: {serviceKey}) service of type {nameof(IStartupOpenGenericServiceProxyRegister)}");
  30.         startupOpenGenericServiceProxyRegister?.Add(serviceType);
  31.         services.TryAdd(new TypedImplementationFactoryServiceDescriptor(
  32.             typeof(IProxyService<>),
  33.             serviceKey,
  34.             (provider, serviceKey, requestedServiceType) =>
  35.             {
  36.                 var proxyServiceType = requestedServiceType.GenericTypeArguments[0];
  37.                 var registered = CheckKeyedOpenGenericServiceProxyRegister(provider, serviceKey, proxyServiceType.GetGenericTypeDefinition());
  38.                 if (!registered) return null!;
  39.                 var proxy = CreateKeyedProxyObject(provider, proxyServiceType, serviceKey, interceptorTypes);
  40.                 return Activator.CreateInstance(typeof(ProxyService<>).MakeGenericType(proxy.GetType()), proxy)!;
  41.             },
  42.             serviceLifetime));
  43.     }
  44.     else
  45.     {
  46.         services.Add(new ServiceDescriptor(
  47.             typeof(IProxyService<>).MakeGenericType(serviceType),
  48.             serviceKey,
  49.             (provider, serviceKey) =>
  50.             {
  51.                 var proxy = CreateKeyedProxyObject(provider, serviceType, serviceKey, interceptorTypes);
  52.                 return Activator.CreateInstance(typeof(ProxyService<>).MakeGenericType(proxy.GetType()), proxy)!;
  53.             },
  54.             serviceLifetime));
  55.     }
  56.     services.TryAddKeyedInterceptors(serviceKey, serviceLifetime, interceptorTypes);
  57.     return services;
  58. }
  59. /// <summary>
  60. /// Adds a implicit proxy for the type specified in <paramref name="serviceType"/> with interceptors
  61. /// specified in <paramref name="interceptorTypes"/> to the specified <see cref="IServiceCollection"/>.
  62. /// </summary>
  63. /// <param name="services">The <see cref="IServiceCollection"/> to add the service proxy to.</param>
  64. /// <param name="serviceType">The type of the service to add proxy.</param>
  65. /// <param name="serviceKey">The <see cref="ServiceDescriptor.ServiceKey"/> of the service.</param>
  66. /// <param name="serviceLifetime">The <see cref="ServiceLifetime"/> of <paramref name="serviceType"/> and <paramref name="interceptorTypes"/>.</param>
  67. /// <param name="interceptorTypes">The interceptor types of the service proxy.</param>
  68. /// <returns>A reference to this instance after the operation has completed.</returns>
  69. /// <remarks>
  70. /// Use key <see cref="ImplicitProxyServiceOriginalServiceKey.CreateOriginalServiceKey(object?)"/>
  71. /// or <see cref="ImplicitProxyServiceOriginalServiceKey.CreateStringOriginalServiceKey(string?)"/> if <paramref name="serviceKey"/> is <see cref="string"/>
  72. /// or <see cref="ImplicitProxyServiceOriginalServiceKey.DefaultStringPrefix"/> + <paramref name="serviceKey"/> if <paramref name="serviceKey"/>
  73. /// is <see cref="string"/>(eg. Constant value for <see cref="FromKeyedServicesAttribute"/>.) to get original service.
  74. /// </remarks>
  75. public static IServiceCollection AddKeyedImplicitProxy(
  76.     this IServiceCollection services,
  77.     Type serviceType,
  78.     object? serviceKey,
  79.     ServiceLifetime serviceLifetime,
  80.     params Type[] interceptorTypes)
  81. {
  82.     ArgumentNullException.ThrowIfNull(services);
  83.     ArgumentNullException.ThrowIfNull(serviceType);
  84.     CheckInterface(serviceType);
  85.     CheckInterceptor(interceptorTypes);
  86.     var originalServiceDescriptor = services.LastOrDefault(service => service.IsKeyedService && service.ServiceKey == serviceKey && service.ServiceType == serviceType && service.Lifetime == serviceLifetime)
  87.         ?? throw new ArgumentException($"Not found registered keyed(key value: {serviceKey}) "{Enum.GetName(serviceLifetime)}" service of type {serviceType.Name}.", nameof(serviceType));
  88.     var newServiceKey = CreateOriginalServiceKey(serviceKey);
  89.     var serviceDescriptorIndex = services.IndexOf(originalServiceDescriptor);
  90.     if (originalServiceDescriptor is TypedImplementationFactoryServiceDescriptor typedServiceDescriptor)
  91.     {
  92.         services.Insert(
  93.             serviceDescriptorIndex,
  94.             new TypedImplementationFactoryServiceDescriptor(
  95.                 typedServiceDescriptor.ServiceType,
  96.                 newServiceKey,
  97.                 (serviceProvider, serviceKey, requestedServiceType) =>
  98.                 {
  99.                     Debug.Assert(serviceKey is ImplicitProxyServiceOriginalServiceKey, $"Implicit proxy not use {nameof(ImplicitProxyServiceOriginalServiceKey)}");
  100.                     return typedServiceDescriptor.TypedKeyedImplementationFactory!(
  101.                         serviceProvider,
  102.                         (serviceKey as ImplicitProxyServiceOriginalServiceKey)?.OriginalServiceKey ?? serviceKey,
  103.                         requestedServiceType);
  104.                 },
  105.                 originalServiceDescriptor.Lifetime)
  106.             );
  107.     }
  108.     else if (originalServiceDescriptor.KeyedImplementationInstance is not null)
  109.     {
  110.         services.Insert(
  111.             serviceDescriptorIndex,
  112.             new ServiceDescriptor(
  113.                 originalServiceDescriptor.ServiceType,
  114.                 newServiceKey,
  115.                 originalServiceDescriptor.KeyedImplementationInstance)
  116.             );
  117.     }
  118.     else if (originalServiceDescriptor.KeyedImplementationType is not null)
  119.     {
  120.         services.Insert(
  121.             serviceDescriptorIndex,
  122.             new ServiceDescriptor(
  123.                 originalServiceDescriptor.ServiceType,
  124.                 newServiceKey,
  125.                 originalServiceDescriptor.KeyedImplementationType,
  126.                 originalServiceDescriptor.Lifetime)
  127.             );
  128.     }
  129.     else if (originalServiceDescriptor.KeyedImplementationFactory is not null)
  130.     {
  131.         services.Insert(
  132.             serviceDescriptorIndex,
  133.             new ServiceDescriptor(
  134.                 originalServiceDescriptor.ServiceType,
  135.                 newServiceKey,
  136.                 (serviceProvider, serviceKey) =>
  137.                 {
  138.                     return originalServiceDescriptor.KeyedImplementationFactory(
  139.                         serviceProvider,
  140.                         serviceKey);
  141.                 },
  142.                 originalServiceDescriptor.Lifetime)
  143.             );
  144.     }
  145.     else throw new Exception("Add proxy service fail.");
  146.     if (serviceType.IsGenericTypeDefinition)
  147.     {
  148.         services.Add(new TypedImplementationFactoryServiceDescriptor(
  149.             serviceType,
  150.             serviceKey,
  151.             (provider, serviceKey, requestedServiceType) =>
  152.             {
  153.                 var newLocalServiceKey = CreateOriginalServiceKey(serviceKey);
  154.                 var proxy = CreateKeyedProxyObject(provider, requestedServiceType, newLocalServiceKey, interceptorTypes);
  155.                 return proxy;
  156.             },
  157.             serviceLifetime));
  158.     }
  159.     else
  160.     {
  161.         services.Add(new ServiceDescriptor(
  162.             serviceType,
  163.             serviceKey,
  164.             (provider, serviceKey) =>
  165.             {
  166.                 var newLocalServiceKey = CreateOriginalServiceKey(serviceKey);
  167.                 var proxy = CreateKeyedProxyObject(provider, serviceType, newLocalServiceKey, interceptorTypes);
  168.                 return proxy;
  169.             },
  170.             serviceLifetime));
  171.     }
  172.     services.TryAddKeyedInterceptors(newServiceKey, serviceLifetime, interceptorTypes);
  173.     services.Remove(originalServiceDescriptor);
  174.     return services;
  175. }
  176.     /// <summary>
  177.     /// Solidify open generic service proxy register for the specified <see cref="IServiceCollection"/>.
  178.     /// </summary>
  179.     /// <param name="containerBuilder">The <see cref="IServiceCollection"/> to solidify register.</param>
  180.     /// <remarks>Should call after last add proxy. If used for host, needn't call.</remarks>
  181.     public static void SolidifyOpenGenericServiceProxyRegister(this IServiceCollection containerBuilder)
  182.     {
  183.         var openGenericServiceProxyRegisters = containerBuilder
  184.             .Where(service => service.ServiceType == typeof(IStartupOpenGenericServiceProxyRegister))
  185.             .ToList();
  186.         var readOnlyOpenGenericServiceProxyRegisters = openGenericServiceProxyRegisters
  187.             .Where(service => service.Lifetime == ServiceLifetime.Singleton)
  188.             .Select(service =>
  189.             {
  190.                 return service.IsKeyedService switch
  191.                 {
  192.                     true => ServiceDescriptor.KeyedSingleton<IOpenGenericServiceProxyRegister>(service.ServiceKey, new OpenGenericServiceProxyRegister((service.KeyedImplementationInstance! as IStartupOpenGenericServiceProxyRegister)!)),
  193.                     false => ServiceDescriptor.Singleton<IOpenGenericServiceProxyRegister>(new OpenGenericServiceProxyRegister((service.ImplementationInstance! as IStartupOpenGenericServiceProxyRegister)!)),
  194.                 };
  195.             });
  196.         foreach (var register in openGenericServiceProxyRegisters)
  197.         {
  198.             containerBuilder.Remove(register);
  199.         }
  200.         foreach (var readOnlyRegister in readOnlyOpenGenericServiceProxyRegisters)
  201.         {
  202.             containerBuilder.Add(readOnlyRegister);
  203.         }
  204.     }
  205.     private static object CreateProxyObject(
  206.         IServiceProvider provider,
  207.         Type serviceType,
  208.         Type[] interceptorTypes)
  209.     {
  210.         var target = provider.GetRequiredService(serviceType);
  211.         var interceptors = interceptorTypes.Select(t => GetInterceptor(provider.GetRequiredService(t))).ToArray();
  212.         var proxyGenerator = provider.GetRequiredService<IProxyGenerator>();
  213.         var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(serviceType, target, interceptors);
  214.         return proxy;
  215.     }
  216.     private static object CreateKeyedProxyObject(
  217.         IServiceProvider provider,
  218.         Type serviceType,
  219.         object? serviceKey,
  220.         Type[] interceptorTypes)
  221.     {
  222.         var target = provider.GetRequiredKeyedService(serviceType, serviceKey);
  223.         var interceptors = interceptorTypes.Select(t => GetInterceptor(provider.GetRequiredKeyedService(t, serviceKey))).ToArray();
  224.         var proxyGenerator = provider.GetRequiredService<IProxyGenerator>();
  225.         var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(serviceType, target, interceptors);
  226.         return proxy;
  227.     }
  228.     private static ImplicitProxyServiceOriginalServiceKey CreateOriginalServiceKey(object? serviceKey)
  229.     {
  230.         return serviceKey switch
  231.         {
  232.             string stringKey => ImplicitProxyServiceOriginalServiceKey.CreateStringOriginalServiceKey(stringKey),
  233.             _ => ImplicitProxyServiceOriginalServiceKey.CreateOriginalServiceKey(serviceKey)
  234.         };
  235.     }
  236.     private static void TryAddInterceptors(
  237.         this IServiceCollection services,
  238.         ServiceLifetime lifetime,
  239.         params Type[] interceptorTypes)
  240.     {
  241.         services.TryAddSingleton<IProxyGenerator, ProxyGenerator>();
  242.         foreach (var interceptorType in interceptorTypes)
  243.         {
  244.             services.TryAdd(new ServiceDescriptor(interceptorType, interceptorType, lifetime));
  245.         }
  246.     }
  247.     private static void TryAddKeyedInterceptors(
  248.         this IServiceCollection services,
  249.         object? serviceKey,
  250.         ServiceLifetime lifetime,
  251.         params Type[] interceptorTypes)
  252.     {
  253.         services.TryAddSingleton<IProxyGenerator, ProxyGenerator>();
  254.         foreach (var interceptorType in interceptorTypes)
  255.         {
  256.             services.TryAdd(new ServiceDescriptor(interceptorType, serviceKey, interceptorType, lifetime));
  257.         }
  258.     }
  259.     private static IInterceptor GetInterceptor(object interceptor)
  260.     {
  261.         return (interceptor as IInterceptor)
  262.             ?? (interceptor as IAsyncInterceptor)?.ToInterceptor()
  263.             ?? throw new InvalidCastException($"{nameof(interceptor)} is not {nameof(IInterceptor)} or {nameof(IAsyncInterceptor)}.");      
  264.     }
  265.     private static void CheckInterface(Type serviceType)
  266.     {
  267.         if (!serviceType.IsInterface)
  268.             throw new InvalidOperationException($"Proxy need interface but {nameof(serviceType)} is not interface.");
  269.     }
  270.     private static void CheckInterceptor(params Type[] types)
  271.     {
  272.         foreach (var type in types)
  273.         {
  274.             if (!(type.IsAssignableTo(typeof(IInterceptor)) || type.IsAssignableTo(typeof(IAsyncInterceptor))))
  275.                 throw new ArgumentException($"Exist element in {nameof(types)} is not {nameof(IInterceptor)} or {nameof(IAsyncInterceptor)}.", $"{nameof(types)}");
  276.         }
  277.     }
  278.     private static bool CheckOpenGenericServiceProxyRegister(IServiceProvider serviceProvider, Type serviceType)
  279.     {
  280.         var register = serviceProvider.GetService<IOpenGenericServiceProxyRegister>();
  281.         CheckOpenGenericServiceProxyRegister(register);
  282.         return register!.Contains(serviceType);
  283.     }
  284.     private static bool CheckKeyedOpenGenericServiceProxyRegister(IServiceProvider serviceProvider, object? serviceKey, Type serviceType)
  285.     {
  286.         var register = serviceProvider.GetKeyedService<IOpenGenericServiceProxyRegister>(serviceKey);
  287.         CheckOpenGenericServiceProxyRegister(register);
  288.         return register!.Contains(serviceType);
  289.     }
  290.     private static void CheckOpenGenericServiceProxyRegister(IOpenGenericServiceProxyRegister? register)
  291.     {
  292.         if (register is null) throw new InvalidOperationException($"Can not found required service of type {nameof(IOpenGenericServiceProxyRegister)}. Maybe you forgot to call method named {nameof(IServiceCollection)}.{nameof(SolidifyOpenGenericServiceProxyRegister)}().");
  293.     }
  294.     private sealed class StartupOpenGenericServiceProxyRegister : List<Type>, IStartupOpenGenericServiceProxyRegister;
复制代码
使用扩展方法把代理完全实现为普通服务注册最大限度减少对服务容器的入侵。对于隐式代理,原始服务会被原地替换为代理服务,原始服务则使用新键重新注册,因此注册代理前需要先注册原始服务。
显式代理的开放泛型处理
  1. public interface IOpenGenericServiceProxyRegister : IReadOnlySet<Type>;
  2. internal interface IStartupOpenGenericServiceProxyRegister : IList<Type>;
  3. public sealed class OpenGenericServiceProxyRegister(IEnumerable<Type> types) : IOpenGenericServiceProxyRegister
  4. {
  5.     private readonly ImmutableHashSet<Type> _types = types.Distinct().ToImmutableHashSet();
  6.     public int Count => _types.Count;
  7.     public bool Contains(Type item) => _types.Contains(item);
  8.     public bool IsProperSubsetOf(IEnumerable<Type> other) => _types.IsProperSubsetOf(other);
  9.     public bool IsProperSupersetOf(IEnumerable<Type> other) => _types.IsProperSupersetOf(other);
  10.     public bool IsSubsetOf(IEnumerable<Type> other) => _types.IsSubsetOf(other);
  11.     public bool IsSupersetOf(IEnumerable<Type> other) => _types.IsSupersetOf(other);
  12.     public bool Overlaps(IEnumerable<Type> other) => _types.Overlaps(other);
  13.     public bool SetEquals(IEnumerable<Type> other) => _types.SetEquals(other);
  14.     public IEnumerator<Type> GetEnumerator() => _types.GetEnumerator();
  15.     IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  16. }
复制代码
显式代理实际上是一个开放泛型服务,因此对于注册过代理的类型需要单独记录,否则无法判断是否应该生成相应的封闭类型。而注册记录在实例化容器后就不应该被修改,因此又提供了SolidifyOpenGenericServiceProxyRegister方法用来固化记录。
CoreDX.Extensions.DependencyInjection.Hosting.Proxies.Abstractions

因为代理服务有一个额外步骤,开发时可能忘记调用,为继续简化和通用主机的集成,把注册记录的固化工作放到主机的容器工厂中进行。
ProxyTypedImplementationFactoryServiceProviderFactory
  1. public class ProxyTypedImplementationFactoryServiceProviderFactory : TypedImplementationFactoryServiceProviderFactory
  2. {
  3.     public ProxyTypedImplementationFactoryServiceProviderFactory() : base() { }
  4.     public ProxyTypedImplementationFactoryServiceProviderFactory(ServiceProviderOptions options) : base(options) { }
  5.     public override IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder)
  6.     {
  7.         containerBuilder.SolidifyOpenGenericServiceProxyRegister();
  8.         return base.CreateServiceProvider(containerBuilder);
  9.     }
  10. }
复制代码
这个工厂唯一的工作就是在内部完成固化操作,这样就可以不用对Startup类做任何修改了。
ProxyTypedImplementationFactoryHostingHostBuilderExtensions
  1. public static class ProxyTypedImplementationFactoryHostingHostBuilderExtensions
  2. {
  3.     /// <summary>
  4.     /// Specify the <see cref="IServiceProvider"/> to be the dynamic proxy and typed implementation factory supported one.
  5.     /// </summary>
  6.     /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to configure.</param>
  7.     /// <returns>The <see cref="IHostBuilder"/>.</returns>
  8.     public static IHostBuilder UseProxyTypedImplementationFactoryServiceProvider(
  9.         this IHostBuilder hostBuilder)
  10.         => hostBuilder.UseProxyTypedImplementationFactoryServiceProvider(static _ => { });
  11.     /// <summary>
  12.     /// Specify the <see cref="IServiceProvider"/> to be the dynamic proxy and typed implementation factory supported one.
  13.     /// </summary>
  14.     /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to configure.</param>
  15.     /// <param name="configure">The delegate that configures the <see cref="IServiceProvider"/>.</param>
  16.     /// <returns>The <see cref="IHostBuilder"/>.</returns>
  17.     public static IHostBuilder UseProxyTypedImplementationFactoryServiceProvider(
  18.         this IHostBuilder hostBuilder,
  19.         Action<ServiceProviderOptions> configure)
  20.         => hostBuilder.UseProxyTypedImplementationFactoryServiceProvider((context, options) => configure(options));
  21.     /// <summary>
  22.     /// Specify the <see cref="IServiceProvider"/> to be the dynamic proxy and typed implementation factory supported one.
  23.     /// </summary>
  24.     /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to configure.</param>
  25.     /// <param name="configure">The delegate that configures the <see cref="IServiceProvider"/>.</param>
  26.     /// <returns>The <see cref="IHostBuilder"/>.</returns>
  27.     public static IHostBuilder UseProxyTypedImplementationFactoryServiceProvider(
  28.         this IHostBuilder hostBuilder,
  29.         Action<HostBuilderContext, ServiceProviderOptions> configure)
  30.     {
  31.         return hostBuilder.UseServiceProviderFactory(context =>
  32.         {
  33.             var options = new ServiceProviderOptions();
  34.             configure(context, options);
  35.             return new ProxyTypedImplementationFactoryServiceProviderFactory(options);
  36.         });
  37.     }
  38. }
复制代码
使用新的扩展方法替换容器工厂即可。
简单使用示例
  1. internal class Program
  2. {
  3.     private static void Main(string[] args)
  4.     {
  5.         Explicit();
  6.         KeyedExplicit();
  7.         Implicit();
  8.         KeyedImplicit();
  9.     }
  10.     private static void Explicit()
  11.     {
  12.         IServiceCollection services = new ServiceCollection();
  13.         services.AddScoped(typeof(IB<>), typeof(B<>));
  14.         services.AddScopedForward(typeof(IA<>), typeof(IB<>));
  15.         services.AddScopedExplicitProxy(typeof(IA<>), typeof(MyInterceptor));
  16.         services.AddScopedExplicitProxy(typeof(IB<>), typeof(MyInterceptor));
  17.         services.SolidifyOpenGenericServiceProxyRegister();
  18.         var sp = services.BuildServiceProvider();
  19.         for(int i = 0; i < 2; i++)
  20.         {
  21.             object? a1 = null, b1 = null;
  22.             using (var scope = sp.CreateScope())
  23.             {
  24.                 var b = scope.ServiceProvider.GetRequiredService<IB<int>>();
  25.                 var a = scope.ServiceProvider.GetRequiredService<IA<int>>();
  26.                 var eqa = ReferenceEquals(a, a1);
  27.                 var eqb = ReferenceEquals(b, b1);
  28.                 a1 = a;
  29.                 b1 = b;
  30.                 var eq = ReferenceEquals(a, b);
  31.                 var pa = scope.ServiceProvider.GetRequiredService<IProxyService<IA<int>>>();
  32.                 var pb = scope.ServiceProvider.GetRequiredService<IProxyService<IB<int>>>();
  33.             }
  34.         }
  35.     }
  36.     private static void KeyedExplicit()
  37.     {
  38.         IServiceCollection services = new ServiceCollection();
  39.         var serviceKey = "Keyed";
  40.         services.AddKeyedScoped(typeof(IB<>), serviceKey, typeof(B<>));
  41.         services.AddKeyedScopedForward(typeof(IA<>), serviceKey, typeof(IB<>));
  42.         services.AddKeyedScopedExplicitProxy(typeof(IA<>), serviceKey, typeof(MyInterceptor));
  43.         services.AddKeyedScopedExplicitProxy(typeof(IB<>), serviceKey, typeof(MyInterceptor));
  44.         services.SolidifyOpenGenericServiceProxyRegister();
  45.         var sp = services.BuildServiceProvider();
  46.         for (int i = 0; i < 2; i++)
  47.         {
  48.             object? a1 = null, b1 = null;
  49.             using (var scope = sp.CreateScope())
  50.             {
  51.                 var b = scope.ServiceProvider.GetRequiredKeyedService<IB<int>>(serviceKey);
  52.                 var a = scope.ServiceProvider.GetRequiredKeyedService<IA<int>>(serviceKey);
  53.                 var eqa = ReferenceEquals(a, a1);
  54.                 var eqb = ReferenceEquals(b, b1);
  55.                 a1 = a;
  56.                 b1 = b;
  57.                 var eq = ReferenceEquals(a, b);
  58.                 var pa = scope.ServiceProvider.GetRequiredKeyedService<IProxyService<IA<int>>>(serviceKey);
  59.                 var pb = scope.ServiceProvider.GetRequiredKeyedService<IProxyService<IB<int>>>(serviceKey);
  60.             }
  61.         }
  62.     }
  63.     private static void Implicit()
  64.     {
  65.         IServiceCollection services = new ServiceCollection();
  66.         services.AddScoped(typeof(IB<>), typeof(B<>));
  67.         services.AddScopedForward(typeof(IA<>), typeof(IB<>));
  68.         services.AddScopedImplicitProxy(typeof(IA<>), typeof(MyInterceptor));
  69.         services.AddScopedImplicitProxy(typeof(IB<>), typeof(MyInterceptor));
  70.         services.SolidifyOpenGenericServiceProxyRegister();
  71.         var sp = services.BuildServiceProvider();
  72.         for (int i = 0; i < 2; i++)
  73.         {
  74.             object? a1 = null, b1 = null;
  75.             using (var scope = sp.CreateScope())
  76.             {
  77.                 var b = scope.ServiceProvider.GetRequiredService<IB<int>>();
  78.                 var a = scope.ServiceProvider.GetRequiredService<IA<int>>();
  79.                 var eqa = ReferenceEquals(a, a1);
  80.                 var eqb = ReferenceEquals(b, b1);
  81.                 a1 = a;
  82.                 b1 = b;
  83.                 var eq = ReferenceEquals(a, b);
  84.                 var ra = scope.ServiceProvider.GetRequiredKeyedService<IA<int>>(ImplicitProxyServiceOriginalServiceKey.StringDefault);
  85.                 var rb = scope.ServiceProvider.GetRequiredKeyedService<IB<int>>(ImplicitProxyServiceOriginalServiceKey.DefaultStringPrefix);
  86.             }
  87.         }
  88.     }
  89.     private static void KeyedImplicit()
  90.     {
  91.         IServiceCollection services = new ServiceCollection();
  92.         var serviceKey = "Keyed";
  93.         services.AddKeyedScoped(typeof(IB<>), serviceKey, typeof(B<>));
  94.         services.AddKeyedScopedForward(typeof(IA<>), serviceKey, typeof(IB<>));
  95.         services.AddKeyedScopedImplicitProxy(typeof(IA<>), serviceKey, typeof(MyInterceptor));
  96.         services.AddKeyedScopedImplicitProxy(typeof(IB<>), serviceKey, typeof(MyInterceptor));
  97.         services.SolidifyOpenGenericServiceProxyRegister();
  98.         var sp = services.BuildServiceProvider();
  99.         for (int i = 0; i < 2; i++)
  100.         {
  101.             object? a1 = null, b1 = null;
  102.             using (var scope = sp.CreateScope())
  103.             {
  104.                 var b = scope.ServiceProvider.GetRequiredKeyedService<IB<int>>(serviceKey);
  105.                 var a = scope.ServiceProvider.GetRequiredKeyedService<IA<int>>(serviceKey);
  106.                 var eqa = ReferenceEquals(a, a1);
  107.                 var eqb = ReferenceEquals(b, b1);
  108.                 a1 = a;
  109.                 b1 = b;
  110.                 var eq = ReferenceEquals(a, b);
  111.                 var ra = scope.ServiceProvider.GetRequiredKeyedService<IA<int>>(ImplicitProxyServiceOriginalServiceKey.CreateStringOriginalServiceKey(serviceKey));
  112.                 var rb = scope.ServiceProvider.GetRequiredKeyedService<IB<int>>($"{ImplicitProxyServiceOriginalServiceKey.DefaultStringPrefix}{serviceKey}");
  113.                 a.M1();
  114.                 b.M1();
  115.                 ra.M1();
  116.                 rb.M1();
  117.             }
  118.         }
  119.     }
  120. }
  121. public interface IA<T>
  122. {
  123.     void M1();
  124. }
  125. public interface IB<T> : IA<T>;
  126. public class B<T> : IB<T>
  127. {
  128.     public void M1()
  129.     {
  130.         Console.WriteLine("B.M1");
  131.     }
  132. }
  133. public class MyInterceptor : IInterceptor
  134. {
  135.     public void Intercept(IInvocation invocation)
  136.     {
  137.         Console.WriteLine("MyInterceptorBefore");
  138.         invocation.Proceed();
  139.         Console.WriteLine("MyInterceptorAfter");
  140.     }
  141. }
复制代码
结语

内置容器新的键控服务把非入侵式代理的服务类型区分问题解决之后让笔者又想起来了这个一直如鲠在喉的问题,结果发现开放泛型还是搞不定,一番纠结后决定自己动手丰衣足食。做到最后感觉反正都这样了,干脆做成Nuget包发布算了,为此又整理了半天文档注释,搞得头晕眼花。
Nuget包版本和代码对应的原始包版本一致。
许可证:MIT
代码仓库:CoreDX.Extensions.DependencyInjection - Github
Nuget:CoreDX.Extensions.DependencyInjection
Nuget:CoreDX.Extensions.DependencyInjection.Abstractions(这个一般不直接用,部分功能依赖改版容器)
Nuget:CoreDX.Extensions.DependencyInjection.Hosting.Abstractions
Nuget:CoreDX.Extensions.DependencyInjection.Hosting.Proxies.Abstractions
Nuget:CoreDX.Extensions.DependencyInjection.Proxies.Abstractions
QQ群

读者交流QQ群:540719365

欢迎读者和广大朋友一起交流,如发现本书错误也欢迎通过博客园、QQ群等方式告知笔者。
本文地址:https://www.cnblogs.com/coredx/p/18138360.html

来源:https://www.cnblogs.com/coredx/p/18138360
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具