前言
.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
提供相应的构造方法重载。原始类型显然不可能,好在这是个普通公共类,可以继承,因此笔者继承内置类并扩展了相应的成员来承载工厂委托。
///
[DebuggerDisplay("{DebuggerToString(),nq}")]
public class TypedImplementationFactoryServiceDescriptor : ServiceDescriptor
{
private object? _typedImplementationFactory;
///
/// Gets the typed factory used for creating service instances.
///
public Func? TypedImplementationFactory
{
get
{
if (IsKeyedService)
{
throw new InvalidOperationException("This service descriptor is keyed. Your service provider may not support keyed services.");
}
return (Func?)_typedImplementationFactory;
}
}
private object? _typedKeyedImplementationFactory;
///
/// Gets the typed keyed factory used for creating service instances.
///
public Func? TypedKeyedImplementationFactory
{
get
{
if (!IsKeyedService)
{
throw new InvalidOperationException("This service descriptor is not keyed.");
}
return (Func?)_typedKeyedImplementationFactory;
}
}
///
/// Don't use this!
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
object instance)
: base(serviceType, instance)
{
ThrowCtor();
}
///
/// Don't use this!
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType,
ServiceLifetime lifetime)
: base(serviceType, implementationType, lifetime)
{
ThrowCtor();
}
///
/// Don't use this!
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
object? serviceKey,
object instance)
: base(serviceType, serviceKey, instance)
{
ThrowCtor();
}
///
/// Don't use this!
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
Func factory,
ServiceLifetime lifetime)
: base(serviceType, factory, lifetime)
{
ThrowCtor();
}
///
/// Don't use this!
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
object? serviceKey,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType,
ServiceLifetime lifetime)
: base(servic服务器托管eType, serviceKey, implementationType, lifetime)
{
ThrowCtor();
}
///
/// Don't use this!
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
object? serviceKey,
Func factory,
ServiceLifetime lifetime)
: base(serviceType, serviceKey, factory, lifetime)
{
ThrowCtor();
}
///
/// Initializes a new instance of with the specified factory.
///
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// The of the service.
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
Func factory,
ServiceLifetime lifetime)
: base(serviceType, ThrowFactory, lifetime)
{
CheckOpenGeneric(serviceType);
_typedImplementationFactory = factory ?? throw new ArgumentNullException(nameof(factory));
}
///
/// Initializes a new instance of with the specified factory.
///
/// The of the service.
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// The of the service.
///
///
public TypedImplementationFactoryServiceDescriptor(
Type serviceType,
object? serviceKey,
Func factory,
ServiceLifetime lifetime)
: base(serviceType, serviceKey, ThrowKeyedFactory, lifetime)
{
CheckOpenGeneric(serviceType);
_typedKeyedImplementationFactory = factory ?? throw new ArgumentNullException(nameof(factory));
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor Singleton(
Type serviceType,
Func implementationFactory)
{
return new(serviceType, implementationFactory, ServiceLifetime.Singleton);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The type of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor Singleton(
Func implementationFactory)
where TService : class
{
return new(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The of the service.
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor KeyedSingleton(
Type serviceType,
object? serviceKey,
Func implementationType)
{
return new(serviceType, serviceKey, implementationType, ServiceLifetime.Singleton);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The type of the service.
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor KeyedSingleton(
object? serviceKey,
Func implementationType)
where TService : class
{
return new(typeof(TService), serviceKey, implementationType, ServiceLifetime.Singleton);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor Scoped(
Type serviceType,
Func implementationType)
{
return new(serviceType, implementationType, ServiceLifetime.Scoped);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The type of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor Scoped(
Func implementationFactory)
where TService : class
{
return new(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The of the service.
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor KeyedScoped(
Type serviceType,
object? serviceKey,
Func implementationType)
{
return new(serviceType, serviceKey, implementationType, ServiceLifetime.Scoped);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The type of the service.
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor KeyedScoped(
object? serviceKey,
Func implementationType)
where TService : class
{
return new(typeof(TService), serviceKey, implementationType, ServiceLifetime.Scoped);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor Transient(
Type serviceType,
Func implementationType)
{
return new(serviceType, implementationType, ServiceLifetime.Transient);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The type of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor Transient(
Func implementationFactory)
where TService : class
{
return new(typeof(TService), implementationFactory, ServiceLifetime.Transient);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The of the service.
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor KeyedTransient(
Type serviceType,
object? serviceKey,
Func implementationType)
{
return new(serviceType, serviceKey, implementationType, ServiceLifetime.Transient);
}
///
/// Creates an instance of
/// with the specified service in and the lifetime.
///
/// The type of the service.
/// The of the service.
/// A factory used for creating service instances. Requested service type is provided as argument in parameter of factory.
/// A new instance of .
public static TypedImplementationFactoryServiceDescriptor KeyedTransient(
object? serviceKey,
Func implementationType)
where TService : class
{
return new(typeof(TService), serviceKey, implementationType, ServiceLifetime.Transient);
}
private string DebuggerToString()
{
string text = $"Lifetime = {Lifetime}, ServiceType = "{ServiceType.FullName}"";
if (IsKeyedService)
{
text += $", ServiceKey = "{ServiceKey}"";
return text + $", TypedKeyedImplementationFactory = {TypedKeyedImplementationFactory!.Method}";
}
else
{
return text + $", TypedImplementationFactory = {TypedImplementationFactory!.Method}";
}
}
private static void ThrowCtor()
{
throw new NotSupportedException($"{nameof(TypedImplementationFactoryServiceDescriptor)} only use for typed factory.");
}
private static object ThrowFactory(IServiceProvider serviceProvider)
{
throw new InvalidOperationException("Please use typed factory instead.");
}
private static object ThrowKeyedFactory(IServiceProvider serviceProvider, object? serviceKey)
{
throw new InvalidOperationException("Please use typed keyed factory instead.");
}
private static void CheckOpenGeneric(Type serviceType)
{
if (!serviceType.IsGenericTypeDefinition)
throw new InvalidOperationException($"{nameof(TypedImplementationFactoryServiceDescriptor)} only used for generic type definition(open generic type).");
}
}
这个类很简单,就是增加了用于保存Func
和Func
工厂委托的字段和配套的构造方法和验证逻辑。基类提供的所有功能均直接抛出异常,专门负责新增功能。
ImplementationFactoryServiceTypeHolder
internal sealed class ImplementationFactoryServiceTypeHolder(Type serviceType)
{
private readonly Func _factory = sp => sp.GetService(serviceType);
public Func Factory => _factory;
}
internal sealed class KeyedImplementationFactoryServiceTypeHolder(Type serviceType)
{
private readonly Func _factory = (sp, key) => (sp as IKeyedServiceProvider)?.GetKeyedService(serviceType, key);
public Func Factory => _factory;
}
internal sealed class OpenGenericImplementationFactoryServiceTypeHolder(Type serviceType)
{
private readonly Func _factory = serviceType.IsGenericTypeDefinition
? (sp, type) =>
{
var closed = serviceType.MakeGenericType(type.GenericTypeArguments);
return sp.GetService(closed);
}
: throw new ArgumentException($"{nameof(serviceType)} is not generic type definition.");
public Func Factory => _factory;
}
internal sealed class KeyedOpenGenericImplementationFactoryServiceTypeHolder(Type serviceType)
{
private readonly Func _factory = serviceType.IsGenericTypeDefinition
? (sp, key, type) =>
{
var closed = serviceType.MakeGenericType(type.GenericTypeArguments);
return (sp as IKeyedServiceProvider)?.GetKeyedService(closed, key);
}
: throw new ArgumentException($"{nameof(serviceType)} is not generic type definition.");
public Func Factory => _factory;
}
这个类也很简单,只负责持有服务类型,并把新的工厂类型转换到原始工厂类型方便集成进内置容器。并且这是内部辅助类型,对开发者是无感知的。
易用性扩展
最后就是提供扩展方法提供和内置容器相似的使用体验。由于本次扩展的主要目的是实现开放发型的服务转发,因此笔者专门准备了一套用来注册服务转发的AddForward
系列扩展方便使用。此处只列出部分预览。
///
/// Adds a service of the type specified in with a factory
/// specified in to the specified .
///
/// The to add the service to.
/// The type of the service to register.
/// The factory that creates the service.
/// The of .
/// A reference to this instance after the operation has completed.
public static IServiceCollection AddTypedFactory(
this IServiceCollection services,
Type serviceType,
Func implementationFactory,
ServiceLifetime serviceLifetime)
{
services.Add(new TypedImplementationFactoryServiceDescriptor(serviceType, implementationFactory, serviceLifetime));
return services;
}
///
/// Adds a service of the type specified in with a factory
/// specified in to the specified .
///
/// The to add the service to.
/// The type of the service to register.
/// The of the service.
/// The factory that creates the service.
/// The of .
/// A reference to this instance after the operation has completed.
public static IServiceCollection AddKeyedTypedFactory(
this IServiceCollection services,
Type serviceType,
object? serviceKey,
Func implementationFactory,
ServiceLifetime serviceLifetime)
{
services.Add(new TypedImplementationFactoryServiceDescriptor(serviceType, serviceKey, implementationFactory, serviceLifetime));
return services;
}
///
/// Adds a service of the type specified in with a forward of the type
/// specified in to the specified .
///
/// The to add the service to.
/// The type of the service to register.
/// The of the service.
/// The forward type of the service.
/// The of .
/// A reference to this instance after the operation has completed.
public static IServiceCollection AddKeyedForward(
this IServiceCollection services,
Type serviceType,
object? serviceKey,
Type forwardTargetServiceType,
ServiceLifetime serviceLifetime)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(serviceType);
ArgumentNullException.ThrowIfNull(forwardTargetServiceType);
if (serviceType.IsGenericTypeDefinition)
{
services.Add(new TypedImplementationFactoryServiceDescriptor(serviceType, serviceKey, new KeyedOpenGenericImplementationFactoryServiceTypeHolder(forwardTargetServiceType).Factory!, serviceLifetime));
}
else
{
services.Add(new ServiceDescriptor(serviceType, serviceKey, new KeyedImplementationFactoryServiceTypeHolder(forwardTargetServiceType).Factory!, serviceLifetime));
}
return services;
}
从示例可以发现如果类型不是开放泛型,是直接使用原始类型进行注册的。也就是说如果安装这个抽象包,但是不使用开放泛型的相关功能,是可以直接用原始内置容器的。
CoreDX.Extensions.DependencyInjection
这是修改后的服务容器实现,增加了对带服务类型的自定义工厂的支持,其他内置功能完全不变。
CallSiteFactory
internal sealed partial class CallSiteFactory : IServiceProviderIsService, IServiceProviderIsKeyedService
{
// 其他原始代码
private void Populate()
{
foreach (ServiceDescriptor descriptor in _descriptors)
{
Type serviceType = descriptor.ServiceType;
#region 验证可识别请求类型的服务实现工厂
if (descriptor is TypedImplementationFactoryServiceDescriptor typedFactoryDescriptor)
{
if(typedFactoryDescriptor.IsKeyedService && typedFactoryDescriptor.TypedKeyedImplementationFactory == null)
{
throw new ArgumentException(
$"Keyed open generic service {serviceType} requires {nameof(typedFactoryDescriptor.TypedKeyedImplementationFactory)}",
"descriptors");
}
else if (!typedFactoryDescriptor.IsKeyedService && typedFactoryDescriptor.TypedImplementationFactory == null)
{
throw new ArgumentException(
$"Open generic service {serviceType} requires {nameof(typedFactoryDescriptor.TypedImplementationFactory)}",
"descriptors");
}
}
#endregion
// 其他原始代码
}
}
private ServiceCallSite? TryCreateExact(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, int slot)
{
if (serviceIdentifier.ServiceType == descriptor.ServiceType)
{
ServiceCacheKey callSiteKey = new ServiceCacheKey(serviceIdentifier, slot);
if (_callSiteCache.TryGetValue(callSiteKey, out ServiceCallSite? serviceCallSite))
{
return serviceCallSite;
}
ServiceCallSite callSite;
var lifetime = new ResultCache(descriptor.Lifetime, serviceIdentifier, slot);
// 其他原始代码
#region 为可识别请求类型的服务工厂注册服务实现工厂
else if (TryCreateTypedFactoryCallSite(lifetime, descriptor as TypedImplementationFactoryServiceDescriptor, descriptor.ServiceType) is ServiceCallSite factoryCallSite)
{
callSite = factoryCallSite;
}
#endregion
// 其他原始代码
return _callSiteCache[callSiteKey] = callSite;
}
return null;
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:MakeGenericType",
Justification = "MakeGenericType here is used to create a closed generic implementation type given the closed service type. " +
"Trimming annotations on the generic types are verified when 'Microsoft.Extensions.DependencyInjection.VerifyOpenGenericServiceTrimmability' is set, which is set by default when PublishTrimmed=true. " +
"That check informs developers when these generic types don't have compatible trimming annotations.")]
[UnconditionalSuppressMessage("AotAnalysis", "IL3050:RequiresDynamicCode",
Justification = "When ServiceProvider.VerifyAotCompatibility is true, which it is by default when PublishAot=true, " +
"this method ensures the generic types being created aren't using ValueTypes.")]
private ServiceCallSite? TryCreateOpenGeneric(ServiceDescriptor descriptor, ServiceIdentifier serviceIdentifier, CallSiteChain callSiteChain, int slot, bool throwOnConstraintViolation)
{
if (serviceIdentifier.IsConstructedGenericType &&
serviceIdentifier.ServiceType.GetGenericTypeDefinition() == descriptor.ServiceType)
{
ServiceCacheKey callSiteKey = new ServiceCacheKey(serviceIdentifier, slot);
if (_callSiteCache.TryGetValue(callSiteKey, out ServiceCallSite? serviceCallSite))
{
return serviceCallSite;
}
Type? implementationType = descriptor.GetImplementationType();
//Debug.Assert(implementationType != null, "descriptor.ImplementationType != null"); // 延迟断言,此处可能是开放泛型工厂
var lifetime = new ResultCache(descriptor.Lifetime, serviceIdentifier, slot);
Type closedType;
try
{
Type[] genericTypeArguments = serviceIdentifier.ServiceType.GenericTypeArguments;
if (TypedImplementationFactoryServiceProvider.VerifyAotCompatibility)
{
VerifyOpenGenericAotCompatibility(serviceIdentifier.ServiceType, genericTypeArguments);
}
#region 为开放式泛型服务添加可识别请求类型的服务实现工厂
if (descriptor is TypedImplementationFactoryServiceDescriptor typedFactoryDescriptor)
{
closedType = typedFactoryDescriptor.ServiceType.MakeGenericType(genericTypeArguments);
if (TryCreateTypedFactoryCallSite(lifetime, typedFactoryDescriptor, closedType) is ServiceCallSite factoryCallSite)
{
return _callSiteCache[callSiteKey] = factoryCallSite;
}
else
{
return null;
}
}
// 断言移动到此处
Debug.Assert(implementationType != null, "descriptor.ImplementationType != null");
#endregion
closedType = implementationType.MakeGenericType(genericTypeArguments);
}
catch (ArgumentException)
{
if (throwOnConstraintViolation)
{
throw;
}
return null;
}
return _callSiteCache[callSiteKey] = CreateConstructorCallSite(lifetime, serviceIdentifier, closedType, callSiteChain);
}
return null;
}
// 其他原始代码
}
这是整个改造的关键,理论上来说只要这个类是普通类的话完全可以直接通过继承把功能加上,可惜不是。此处只展示修改的部分。然后把辅助方法定义到另一个文件,方便利用部分类的特点尽量减少对原始代码的改动,方便将来同步官方代码。
internal sealed partial class CallSiteFactory
{
///
/// 尝试创建可识别请求类型的工厂调用点
///
///
///
/// 服务类型
///
private static FactoryCallSite? TryCreateTypedFactoryCallSite(
ResultCache lifetime,
TypedImplementationFactoryServiceDescriptor? descriptor,
Type serviceType)
{
ArgumentNullException.ThrowIfNull(serviceType);
if (descriptor == null) { }
else if (descriptor.IsKeyedService && descriptor.TypedKeyedImplementationFactory != null)
{
return new FactoryCallSite(lifetime, descriptor.ServiceType, descriptor.ServiceKey!, new TypedKeyedServiceImplementationFactoryHolder(descriptor.TypedKeyedImplementationFactory!, serviceType).Factory);
}
else if (!descriptor.IsKeyedService && descriptor.TypedImplementationFactory != null)
{
return new FactoryCallSite(lifetime, descriptor.ServiceType, new TypedServiceImplementationFactoryHolder(descriptor.TypedImplementationFactory!, serviceType).Factory);
}
return null;
}
}
TypedServiceImplementationFactoryHolder
internal sealed class TypedServiceImplementationFactoryHolder
{
private readonly Func _factory;
private readonly Type _serviceType;
internal TypedServiceImplementationFactoryHolder(Func factory, Type serviceType)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_serviceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType));
}
internal Func Factory => FactoryFunc;
private object FactoryFunc(IServiceProvider provider)
{
return _factory(provider, _serviceType);
}
}
internal sealed class TypedKeyedServiceImplementationFactoryHolder
{
private readonly Func _factory;
private readonly Type _serviceType;
internal TypedKeyedServiceImplementationFactoryHolder(Func factory, Type serviceType)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_serviceType = serviceType ?? throw new ArgumentNullException(nameof(serviceType));
}
internal Func Factory => FactoryFunc;
private object FactoryFunc(IServiceProvider provider, object? serviceKey)
{
return _factory(provider, serviceKey, _serviceType);
}
}
因为笔者直接使用了内置类型,因此需要把工厂委托转换成内置容器支持的签名。Holder辅助类就可以把类型信息保存为内部字段,对外暴露的工厂签名就可以不需要类型参数了。
最后为避免引起误解,笔者修改了类名,但保留文件名方便比对原始仓库代码。至此,改造其实已经完成。可以看出改动真的很少,不知道为什么微软就是不改。
CoreDX.Extensions.DependencyInjection.Hosting.Abstractions
虽然经过上面的改造后,改版容器已经能用了,但是为了方便和通用主机系统集成还是要提供一个替换容器用的扩展。
TypedImplementationFactoryHostingHostBuilderExtensions
public static class TypedImplementationFactoryHostingHostBuilderExtensions
{
///
/// Specify the to be the typed implementation factory supported one.
///
/// The to configure.
/// The .
public static IHostBuilder UseTypedImplementationFactoryServiceProvider(
this IHostBuilder hostBuilder)
=> hostBuilder.UseTypedImplementationFactoryServiceProvider(static _ => { });
///
/// Specify the to be the typed implementation factory supported one.
///
/// The to configure.
/// The delegate that configures the .
/// The .
public static IHostBuilder UseTypedImplementationFactoryServiceProvider(
this IHostBuilder hostBuilder,
Action configure)
=> hostBuilder.UseTypedImplementationFactoryServiceProvider((context, options) => configure(options));
///
/// Specify the to be the typed implementation factory supported one.
///
/// The to configure.
/// The delegate that configures the .
/// The .
public static IHostBuilder UseTypedImplementationFactoryServiceProvider(
this IHostBuilder hostBuilder,
Action configure)
{
return hostBuilder.UseServiceProviderFactory(context =>
{
var options = new ServiceProviderOptions();
configure(context, options);
return new TypedImplementationFactoryServiceProviderFactory(options);
});
}
}
至此,主机集成工作也完成了。本来打算就这么结束的,结果突然想起来,开放泛型问题解决了,键控服务也有了,之前一直不知道怎么办的动态代理貌似是有戏了,就又研究起来了。
CoreDX.Extensions.DependencyInjection.Proxies.Abstractions
之前动态代理不好实现主要是因为代理服务和原始服务的注册类型相同,实在是没办法。既然现在有键控服务了,那么把原始服务和代理服务用键分开就完美搞定,最后一个问题就是键要怎么处理。通过文档可知键控服务的键可以是任意object
,只要实现合理的相等性判断即可。因此笔者决定使用专用的类型来表示代理服务的键,并通过对string
类型的特殊处理来实现特性键指定的兼容。
ImplicitProxyServiceOriginalServiceKey
///
/// Service key for access original service that already added as implicit proxy.
///
public sealed class ImplicitProxyServiceOriginalServiceKey
: IEquatable
#if NET7_0_OR_GREATER
, IEqualityOperators
, IEqualityOperators
#endif
{
private const int _hashCodeBase = 870983858;
private readonly bool _isStringMode;
private readonly object? _originalServiceKey;
private static readonly ImplicitProxyServiceOriginalServiceKey _default = CreateOriginalServiceKey(null);
private static readonly ImplicitProxyServiceOriginalServiceKey _stringDefault = CreateStringOriginalServiceKey(null);
///
/// Prefix for access original based keyed service that already added as implicit proxy.
///
public const string DefaultStringPrefix = $"[{nameof(CoreDX)}.{nameof(Extensions)}.{nameof(DependencyInjection)}.{nameof(Proxies)}.{nameof(ImplicitProxyServiceOriginalServiceKey)}](ImplicitDefault)";
///
/// Default original service key for none keyed proxy service.
///
public static ImplicitProxyServiceOriginalServiceKey Default => _default;
///
/// Default original service key for none based keyed proxy service.
///
public static ImplicitProxyServiceOriginalServiceKey StringDefault => _stringDefault;
///
/// Service key of original service.
///
public object? OriginalServiceKey => _originalServiceKey;
public bool Equals(ImplicitProxyServiceOriginalServiceKey? other)
{
return Equals((object?)other);
}
public override bool Equals(object? obj)
{
if (_isStringMode && obj is string str) return $"{DefaultStringPrefix}{_originalServiceKey}" == str;
else
{
var isEquals = obj is not null and ImplicitProxyServiceOriginalServiceKey other
&& ((_originalServiceKey is null && other._originalServiceKey is null) || _originalServiceKey?.Equals(other._originalServiceKey) is true);
return isEquals;
}
}
public static bool operator ==(ImplicitProxyServiceOriginalServiceKey? left, ImplicitProxyServiceOriginalServiceKey? right)
{
return left?.Equals(right) is true;
}
public static bool operator !=(ImplicitProxyServiceOriginalServiceKey? left, ImplicitProxyServiceOriginalServiceKey? right)
{
return !(left == right);
}
public static bool operator ==(ImplicitProxyServiceOriginalServiceKey? left, object? right)
{
return left?.Equals(right) is true;
}
public static bool operator !=(ImplicitProxyServiceOriginalServiceKey? left, object? right)
{
return !(left == right);
}
public static bool operator ==(object? left, ImplicitProxyServiceOriginalServiceKey? right)
{
return right == left;
}
public static bool operator !=(object? left, ImplicitProxyServiceOriginalServiceKey? right)
{
return right != left;
}
public override int GetHashCode()
{
return _isStringMode
? $"{DefaultStringPrefix}{_originalServiceKey}".GetHashCode()
: HashCode.Combine(_hashCodeBase, _originalServiceKey);
}
///
/// Creates an instance of with the specified service key in .
///
///
/// A new instance of .
public static ImplicitProxyServiceOriginalServiceKey CreateOriginalServiceKey(object? originalServiceKey)
{
return new(originalServiceKey, false);
}
///
/// Creates an instance of with the specified based service key in .
///
///
/// A new instance of .
public static ImplicitProxyServiceOriginalServiceKey CreateStringOriginalServiceKey(string? originalServiceKey)
{
return new(originalServiceKey, true);
}
private ImplicitProxyServiceOriginalServiceKey(object? originalServiceKey, bool isStringMode)
{
_originalServiceKey = originalServiceKey;
_isStringMode = isStringMode;
}
}
对.NET 7以上版本,把运算符实现为接口。
ProxyService
///
/// The interface for get explicit proxy service.
///
/// The type of original service to get explicit proxy.
public interface IProxyService
where TService : class
{
///
/// Get proxy service instance of type .
///
TService Proxy { get; }
}
///
/// The type for get explicit proxy service.
///
/// The type of original service to get explicit proxy.
/// Object instance of original service to be proxy.
internal sealed class ProxyService(TService service) : IProxyService
where TService : class
{
public TService Proxy { get; } = service;
}
除了隐式代理,笔者还准备了显式代理,这也是笔者要在内置容器上扩展而不是去用其他第三方容器的一个原因。第三方容器代理后原始服务就被隐藏了,在某些极端情况下万一要用到原始服务就没办法了。
CastleDynamicProxyDependencyInjectionExtensions
此处只展示部分预览。
///
/// Adds a explicit proxy for the type specified in with interceptors
/// specified in to the specified .
///
/// The to add the service proxy to.
/// The of the service.
/// The type of the service to add proxy.
/// The of and .
/// The interceptor types of the service proxy.
/// A reference to this instance after the operation has completed.
/// Use to get proxy service.
public static IServiceCollection AddKeyedExplicitProxy(
this IServiceCollection services,
Type serviceType,
object? serviceKey,
ServiceLifetime serviceLifetime,
params Type[] interceptorTypes)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(serviceType);
CheckInterface(serviceType);
CheckInterceptor(interceptorTypes);
if (serviceType.IsGenericTypeDefinition)
{
services.TryAddKeyedSingleton(serviceKey, new StartupOpenGenericServiceProxyRegister());
var startupOpenGenericServiceProxyRegister = services
.LastOrDefault(service => service.IsKeyedService && service.ServiceKey == serviceKey && service.ServiceType == typeof(IStartupOpenGenericServiceProxyRegister))
?.KeyedImplementationInstance as IStartupOpenGenericServiceProxyRegister
?? throw new InvalidOperationException($"Can not found keyed(key value: {serviceKey}) service of type {nameof(IStartupOpenGenericServiceProxyRegister)}");
startupOpenGenericServiceProxyRegister?.Add(serviceType);
services.TryAdd(new TypedImplementationFactoryServiceDescriptor(
typeof(IProxyService),
serviceKey,
(provider, serviceKey, requestedServiceType) =>
{
var proxyServiceType = requestedServiceType.GenericTypeArguments[0];
var registered = CheckKeyedOpenGenericServiceProxyRegister(provider, serviceKey, proxyServiceType.GetGenericTypeDefinition());
if (!registered) return null!;
var proxy = CreateKeyedProxyObject(provider, proxyServiceType, serviceKey, interceptorTypes);
return Activator.CreateInstance(typeof(ProxyService).MakeGenericType(proxy.GetType()), proxy)!;
},
serviceLifetime));
}
else
{
services.Add(new ServiceDescriptor(
typeof(IProxyService).MakeGenericType(serviceType),
serviceKey,
(provider, serviceKey) =>
{
var proxy = CreateKeyedProxyObject(provider, serviceType, serviceKey, interceptorTypes);
return Activator.CreateInstance(typeof(ProxyService).MakeGenericType(proxy.GetType()), proxy)!;
},
serviceLifetime));
}
services.TryAddKeyedInterceptors(serviceKey, serviceLifetime, interceptorTypes);
return services;
}
///
/// Adds a implicit proxy for the type specified in with interceptors
/// specified in to the specified .
///
/// The to add the service proxy to.
/// The type of the service to add proxy.
/// The of the service.
/// The of and .
/// The interceptor types of the service proxy.
/// A reference to this instance after the operation has completed.
///
/// Use key
/// or if is
/// or + if
/// is (eg. Constant value for .) to get original service.
///
public static IServiceCollection AddKeyedImplicitProxy(
this IServiceCollection services,
Type serviceType,
object? serviceKey,
ServiceLifetime serviceLifetime,
params Type[] interceptorTypes)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(serviceType);
CheckInterface(serviceType);
CheckInterceptor(interceptorTypes);
var originalServiceDescriptor = services.LastOrDefault(service => service.IsKeyedService && service.ServiceKey == serviceKey && service.ServiceType == serviceType && service.Lifetime == serviceLifetime)
?? throw new ArgumentException($"Not found registered keyed(key value: {serviceKey}) "{Enum.GetName(serviceLifetime)}" service of type {serviceType.Name}.", nameof(serviceType));
var newServiceKey = CreateOriginalServiceKey(serviceKey);
var serviceDescriptorIndex = services.IndexOf(originalServiceDescriptor);
if (originalServiceDescriptor is TypedImplementationFactoryServiceDescriptor typedServiceDescriptor)
{
services.Insert(
serviceDescriptorIndex,
new TypedImplementationFactoryServiceDescriptor(
typedServiceDescriptor.ServiceType,
newServiceKey,
(serviceProvider, serviceKey, requestedServiceType) =>
{
Debug.Assert(serviceKey is ImplicitProxyServiceOriginalServiceKey, $"Implicit proxy not use {nameof(ImplicitProxyServiceOriginalServiceKey)}");
return typedServiceDescriptor.TypedKeyedImplementationFactory!(
serviceProvider,
(serviceKey as ImplicitProxyServiceOriginalServiceKey)?.OriginalServiceKey ?? serviceKey,
requestedServiceType);
},
originalServiceDescriptor.Lifetime)
);
}
else if (originalServiceDescriptor.KeyedImplementationInstance is not null)
{
services.Insert(
serviceDescriptorIndex,
new ServiceDescriptor(
originalServiceDescriptor.ServiceType,
newServiceKey,
originalServiceDescriptor.KeyedImplementationInstance)
);
}
else if (originalServiceDescriptor.KeyedImplementationType is not null)
{
services.Insert(
serviceDescriptorIndex,服务器托管
new ServiceDescriptor(
originalServiceDescriptor.ServiceType,
newServiceKey,
originalServiceDescriptor.KeyedImplementationType,
originalServiceDescriptor.Lifetime)
);
}
else if (originalServiceDescriptor.KeyedImplementationFactory is not null)
{
services.Insert(
serviceDescriptorIndex,
new ServiceDescriptor(
originalServiceDescriptor.ServiceType,
newServiceKey,
(serviceProvider, serviceKey) =>
{
return originalServiceDescriptor.KeyedImplementationFactory(
serviceProvider,
serviceKey);
},
originalServiceDescriptor.Lifetime)
);
}
else throw new Exception("Add proxy service fail.");
if (serviceType.IsGenericTypeDefinition)
{
services.Add(new TypedImplementationFactoryServiceDescriptor(
serviceType,
serviceKey,
(provider, serviceKey, requestedServiceType) =>
{
var newLocalServiceKey = CreateOriginalServiceKey(serviceKey);
var proxy = CreateKeyedProxyObject(provider, requestedServiceType, newLocalServiceKey, interceptorTypes);
return proxy;
},
serviceLifetime));
}
else
{
services.Add(new ServiceDescriptor(
serviceType,
serviceKey,
(provider, serviceKey) =>
{
var newLocalServiceKey = CreateOriginalServiceKey(serviceKey);
var proxy = CreateKeyedProxyObject(provider, serviceType, newLocalServiceKey, interceptorTypes);
return proxy;
},
serviceLifetime));
}
services.TryAddKeyedInterceptors(newServiceKey, serviceLifetime, interceptorTypes);
services.Remove(originalServiceDescriptor);
return services;
}
///
/// Solidify open generic service proxy register for the specified .
///
/// The to solidify register.
/// Should call after last add proxy. If used for host, needn't call.
public static void SolidifyOpenGenericServiceProxyRegister(this IServiceCollection containerBuilder)
{
var openGenericServiceProxyRegisters = containerBuilder
.Where(service => service.ServiceType == typeof(IStartupOpenGenericServiceProxyRegister))
.ToList();
var readOnlyOpenGenericServiceProxyRegisters = openGenericServiceProxyRegisters
.Where(service => service.Lifetime == ServiceLifetime.Singleton)
.Select(service =>
{
return service.IsKeyedService switch
{
true => ServiceDescriptor.KeyedSingleton(service.ServiceKey, new OpenGenericServiceProxyRegister((service.KeyedImplementationInstance! as IStartupOpenGenericServiceProxyRegister)!)),
false => ServiceDescriptor.Singleton(new OpenGenericServiceProxyRegister((service.ImplementationInstance! as IStartupOpenGenericServiceProxyRegister)!)),
};
});
foreach (var register in openGenericServiceProxyRegisters)
{
containerBuilder.Remove(register);
}
foreach (var readOnlyRegister in readOnlyOpenGenericServiceProxyRegisters)
{
containerBuilder.Add(readOnlyRegister);
}
}
private static object CreateProxyObject(
IServiceProvider provider,
Type serviceType,
Type[] interceptorTypes)
{
var target = provider.GetRequiredService(serviceType);
var interceptors = interceptorTypes.Select(t => GetInterceptor(provider.GetRequiredService(t))).ToArray();
var proxyGenerator = provider.GetRequiredService();
var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(serviceType, target, interceptors);
return proxy;
}
private static object CreateKeyedProxyObject(
IServiceProvider provider,
Type serviceType,
object? serviceKey,
Type[] interceptorTypes)
{
var target = provider.GetRequiredKeyedService(serviceType, serviceKey);
var interceptors = interceptorTypes.Select(t => GetInterceptor(provider.GetRequiredKeyedService(t, serviceKey))).ToArray();
var proxyGenerator = provider.GetRequiredService();
var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(serviceType, target, interceptors);
return proxy;
}
private static ImplicitProxyServiceOriginalServiceKey CreateOriginalServiceKey(object? serviceKey)
{
return serviceKey switch
{
string stringKey => ImplicitProxyServiceOriginalServiceKey.CreateStringOriginalServiceKey(stringKey),
_ => ImplicitProxyServiceOriginalServiceKey.CreateOriginalServiceKey(serviceKey)
};
}
private static void TryAddInterceptors(
this IServiceCollection services,
ServiceLifetime lifetime,
params Type[] interceptorTypes)
{
services.TryAddSingleton();
foreach (var interceptorType in interceptorTypes)
{
services.TryAdd(new ServiceDescriptor(interceptorType, interceptorType, lifetime));
}
}
private static void TryAddKeyedInterceptors(
this IServiceCollection services,
object? serviceKey,
ServiceLifetime lifetime,
params Type[] interceptorTypes)
{
services.TryAddSingleton();
foreach (var interceptorType in interceptorTypes)
{
services.TryAdd(new ServiceDescriptor(interceptorType, serviceKey, interceptorType, lifetime));
}
}
private static IInterceptor GetInterceptor(object interceptor)
{
return (interceptor as IInterceptor)
?? (interceptor as IAsyncInterceptor)?.ToInterceptor()
?? throw new InvalidCastException($"{nameof(interceptor)} is not {nameof(IInterceptor)} or {nameof(IAsyncInterceptor)}.");
}
private static void CheckInterface(Type serviceType)
{
if (!serviceType.IsInterface)
throw new InvalidOperationException($"Proxy need interface but {nameof(serviceType)} is not interface.");
}
private static void CheckInterceptor(params Type[] types)
{
foreach (var type in types)
{
if (!(type.IsAssignableTo(typeof(IInterceptor)) || type.IsAssignableTo(typeof(IAsyncInterceptor))))
throw new ArgumentException($"Exist element in {nameof(types)} is not {nameof(IInterceptor)} or {nameof(IAsyncInterceptor)}.", $"{nameof(types)}");
}
}
private static bool CheckOpenGenericServiceProxyRegister(IServiceProvider serviceProvider, Type serviceType)
{
var register = serviceProvider.GetService();
CheckOpenGenericServiceProxyRegister(register);
return register!.Contains(serviceType);
}
private static bool CheckKeyedOpenGenericServiceProxyRegister(IServiceProvider serviceProvider, object? serviceKey, Type serviceType)
{
var register = serviceProvider.GetKeyedService(serviceKey);
CheckOpenGenericServiceProxyRegister(register);
return register!.Contains(serviceType);
}
private static void CheckOpenGenericServiceProxyRegister(IOpenGenericServiceProxyRegister? register)
{
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)}().");
}
private sealed class StartupOpenGenericServiceProxyRegister : List, IStartupOpenGenericServiceProxyRegister;
使用扩展方法把代理完全实现为普通服务注册最大限度减少对服务容器的入侵。对于隐式代理,原始服务会被原地替换为代理服务,原始服务则使用新键重新注册,因此注册代理前需要先注册原始服务。
显式代理的开放泛型处理
public interface IOpenGenericServiceProxyRegister : IReadOnlySet;
internal interface IStartupOpenGenericServiceProxyRegister : IList;
public sealed class OpenGenericServiceProxyRegister(IEnumerable types) : IOpenGenericServiceProxyRegister
{
private readonly ImmutableHashSet _types = types.Distinct().ToImmutableHashSet();
public int Count => _types.Count;
public bool Contains(Type item) => _types.Contains(item);
public bool IsProperSubsetOf(IEnumerable other) => _types.IsProperSubsetOf(other);
public bool IsProperSupersetOf(IEnumerable other) => _types.IsProperSupersetOf(other);
public bool IsSubsetOf(IEnumerable other) => _types.IsSubsetOf(other);
public bool IsSupersetOf(IEnumerable other) => _types.IsSupersetOf(other);
public bool Overlaps(IEnumerable other) => _types.Overlaps(other);
public bool SetEquals(IEnumerable other) => _types.SetEquals(other);
public IEnumerator GetEnumerator() => _types.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
显式代理实际上是一个开放泛型服务,因此对于注册过代理的类型需要单独记录,否则无法判断是否应该生成相应的封闭类型。而注册记录在实例化容器后就不应该被修改,因此又提供了SolidifyOpenGenericServiceProxyRegister
方法用来固化记录。
CoreDX.Extensions.DependencyInjection.Hosting.Proxies.Abstractions
因为代理服务有一个额外步骤,开发时可能忘记调用,为继续简化和通用主机的集成,把注册记录的固化工作放到主机的容器工厂中进行。
ProxyTypedImplementationFactoryServiceProviderFactory
public class ProxyTypedImplementationFactoryServiceProviderFactory : TypedImplementationFactoryServiceProviderFactory
{
public ProxyTypedImplementationFactoryServiceProviderFactory() : base() { }
public ProxyTypedImplementationFactoryServiceProviderFactory(ServiceProviderOptions options) : base(options) { }
public override IServiceProvider CreateServiceProvider(IServiceCollection containerBuilder)
{
containerBuilder.SolidifyOpenGenericServiceProxyRegister();
return base.CreateServiceProvider(containerBuilder);
}
}
这个工厂唯一的工作就是在内部完成固化操作,这样就可以不用对Startup
类做任何修改了。
ProxyTypedImplementationFactoryHostingHostBuilderExtensions
public static class ProxyTypedImplementationFactoryHostingHostBuilderExtensions
{
///
/// Specify the to be the dynamic proxy and typed implementation factory supported one.
///
/// The to configure.
/// The .
public static IHostBuilder UseProxyTypedImplementationFactoryServiceProvider(
this IHostBuilder hostBuilder)
=> hostBuilder.UseProxyTypedImplementationFactoryServiceProvider(static _ => { });
///
/// Specify the to be the dynamic proxy and typed implementation factory supported one.
///
/// The to configure.
/// The delegate that configures the .
/// The .
public static IHostBuilder UseProxyTypedImplementationFactoryServiceProvider(
this IHostBuilder hostBuilder,
Action configure)
=> hostBuilder.UseProxyTypedImplementationFactoryServiceProvider((context, options) => configure(options));
///
/// Specify the to be the dynamic proxy and typed implementation factory supported one.
///
/// The to configure.
/// The delegate that configures the .
/// The .
public static IHostBuilder UseProxyTypedImplementationFactoryServiceProvider(
this IHostBuilder hostBuilder,
Action configure)
{
return hostBuilder.UseServiceProviderFactory(context =>
{
var options = new ServiceProviderOptions();
configure(context, options);
return new ProxyTypedImplementationFactoryServiceProviderFactory(options);
});
}
}
使用新的扩展方法替换容器工厂即可。
简单使用示例
internal class Program
{
private static void Main(string[] args)
{
Explicit();
KeyedExplicit();
Implicit();
KeyedImplicit();
}
private static void Explicit()
{
IServiceCollection services = new ServiceCollection();
services.AddScoped(typeof(IB), typeof(B));
services.AddScopedForward(typeof(IA), typeof(IB));
services.AddScopedExplicitProxy(typeof(IA), typeof(MyInterceptor));
services.AddScopedExplicitProxy(typeof(IB), typeof(MyInterceptor));
services.SolidifyOpenGenericServiceProxyRegister();
var sp = services.BuildServiceProvider();
for(int i = 0; i >();
var a = scope.ServiceProvider.GetRequiredService>();
var eqa = ReferenceEquals(a, a1);
var eqb = ReferenceEquals(b, b1);
a1 = a;
b1 = b;
var eq = ReferenceEquals(a, b);
var pa = scope.ServiceProvider.GetRequiredService>>();
var pb = scope.ServiceProvider.GetRequiredService>>();
}
}
}
private static void KeyedExplicit()
{
IServiceCollection services = new ServiceCollection();
var serviceKey = "Keyed";
services.AddKeyedScoped(typeof(IB), serviceKey, typeof(B));
services.AddKeyedScopedForward(typeof(IA), serviceKey, typeof(IB));
services.AddKeyedScopedExplicitProxy(typeof(IA), serviceKey, typeof(MyInterceptor));
services.AddKeyedScopedExplicitProxy(typeof(IB), serviceKey, typeof(MyInterceptor));
services.SolidifyOpenGenericServiceProxyRegister();
var sp = services.BuildServiceProvider();
for (int i = 0; i >(serviceKey);
var a = scope.ServiceProvider.GetRequiredKeyedService>(serviceKey);
var eqa = ReferenceEquals(a, a1);
var eqb = ReferenceEquals(b, b1);
a1 = a;
b1 = b;
var eq = ReferenceEquals(a, b);
var pa = scope.ServiceProvider.GetRequiredKeyedService>>(serviceKey);
var pb = scope.ServiceProvider.GetRequiredKeyedService>>(serviceKey);
}
}
}
private static void Implicit()
{
IServiceCollection services = new ServiceCollection();
services.AddScoped(typeof(IB), typeof(B));
services.AddScopedForward(typeof(IA), typeof(IB));
services.AddScopedImplicitProxy(typeof(IA), typeof(MyInterceptor));
services.AddScopedImplicitProxy(typeof(IB), typeof(MyInterceptor));
services.SolidifyOpenGenericServiceProxyRegister();
var sp = services.BuildServiceProvider();
for (int i = 0; i >();
var a = scope.ServiceProvider.GetRequiredService>();
var eqa = ReferenceEquals(a, a1);
var eqb = ReferenceEquals(b, b1);
a1 = a;
b1 = b;
var eq = ReferenceEquals(a, b);
var ra = scope.ServiceProvider.GetRequiredKeyedService>(ImplicitProxyServiceOriginalServiceKey.StringDefault);
var rb = scope.ServiceProvider.GetRequiredKeyedService>(ImplicitProxyServiceOriginalServiceKey.DefaultStringPrefix);
}
}
}
private static void KeyedImplicit()
{
IServiceCollection services = new ServiceCollection();
var serviceKey = "Keyed";
services.AddKeyedScoped(typeof(IB), serviceKey, typeof(B));
services.AddKeyedScopedForward(typeof(IA), serviceKey, typeof(IB));
services.AddKeyedScopedImplicitProxy(typeof(IA), serviceKey, typeof(MyInterceptor));
services.AddKeyedScopedImplicitProxy(typeof(IB), serviceKey, typeof(MyInterceptor));
services.SolidifyOpenGenericServiceProxyRegister();
var sp = services.BuildServiceProvider();
for (int i = 0; i >(serviceKey);
var a = scope.ServiceProvider.GetRequiredKeyedService>(serviceKey);
var eqa = ReferenceEquals(a, a1);
var eqb = ReferenceEquals(b, b1);
a1 = a;
b1 = b;
var eq = ReferenceEquals(a, b);
var ra = scope.ServiceProvider.GetRequiredKeyedService>(ImplicitProxyServiceOriginalServiceKey.CreateStringOriginalServiceKey(serviceKey));
var rb = scope.ServiceProvider.GetRequiredKeyedService>($"{ImplicitProxyServiceOriginalServiceKey.DefaultStringPrefix}{serviceKey}");
a.M1();
b.M1();
ra.M1();
rb.M1();
}
}
}
}
public interface IA
{
void M1();
}
public interface IB : IA;
public class B : IB
{
public void M1()
{
Console.WriteLine("B.M1");
}
}
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("MyInterceptorBefore");
invocation.Proceed();
Console.WriteLine("MyInterceptorAfter");
}
}
结语
内置容器新的键控服务把非入侵式代理的服务类型区分问题解决之后让笔者又想起来了这个一直如鲠在喉的问题,结果发现开放泛型还是搞不定,一番纠结后决定自己动手丰衣足食。做到最后感觉反正都这样了,干脆做成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
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
相关推荐: Windows中的Git Bash运行conda命令:未找到命令的错误(已解决)
在windows中的Gitbash中 打开激活conda环境,并运行(前提是你先安装好git(自己去官网下载))。 要能够在Gitbash上运行Conda, 临时配置 如果你只是临时用一下,就是临时爽一把,那就按照下面的设置(如果你的Aanconda3安装在c…