zoukankan      html  css  js  c++  java
  • .NET Core-IServiceCollection扩展一个Replace方法

    Replace方法可替换掉之前注入的服务,比如我们可以替换框架中用到的服务,达到修改源码的目的

        public static class ServiceCollectionExtensions
        {
            public static IServiceCollection Replace<TService, TImplementation>(this IServiceCollection services)
                where TImplementation : TService
            {
                return services.Replace<TService>(typeof(TImplementation));
            }
    
            public static IServiceCollection Replace<TService>(this IServiceCollection services, Type implementationType)
            {
                return services.Replace(typeof(TService), implementationType);
            }
    
            public static IServiceCollection Replace(this IServiceCollection services, Type serviceType, Type implementationType)
            {
                if (services == null)
                {
                    throw new ArgumentNullException(nameof(services));
                }
    
                if (serviceType == null)
                {
                    throw new ArgumentNullException(nameof(serviceType));
                }
    
                if (implementationType == null)
                {
                    throw new ArgumentNullException(nameof(implementationType));
                }
    
                if (!services.TryGetDescriptors(serviceType, out var descriptors))
                {
                    throw new ArgumentException($"No services found for {serviceType.FullName}.", nameof(serviceType));
                }
    
                foreach (var descriptor in descriptors)
                {
                    var index = services.IndexOf(descriptor);
    
                    services.Insert(index, descriptor.WithImplementationType(implementationType));
    
                    services.Remove(descriptor);
                }
    
                return services;
            }
    
            private static bool TryGetDescriptors(this IServiceCollection services, Type serviceType, out ICollection<ServiceDescriptor> descriptors)
            {
                return (descriptors = services.Where(service => service.ServiceType == serviceType).ToArray()).Any();
            }
    
            private static ServiceDescriptor WithImplementationType(this ServiceDescriptor descriptor, Type implementationType)
            {
                return new ServiceDescriptor(descriptor.ServiceType, implementationType, descriptor.Lifetime);
            }
        }
    
  • 相关阅读:
    .net core 认证与授权(三)
    .net core 认证与授权(二)
    .net core 认证与授权(一)
    算法常识——快速排序
    ip 在网络传输中是如何传递的
    打开c++ 项目遇到的错误
    算法常识——鸡尾酒排序
    算法常识——冒泡排序
    算法常识——排序汇
    Tomcat 生产服务器性能优化
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/14489748.html
Copyright © 2011-2022 走看看