private static void ShimActivatorUtilitiesConstructorAttributeTypes()

in src/WebJobs.Script.WebHost/DependencyInjection/JobHostScopedServiceProviderFactory.cs [143:198]


        private static void ShimActivatorUtilitiesConstructorAttributeTypes(IServiceCollection services, ILogger logger)
        {
            Dictionary<ServiceDescriptor, ServiceDescriptor> toReplace = null;
            static bool HasPreferredCtor(Type type)
            {
                foreach (ConstructorInfo c in type.GetConstructors())
                {
                    if (c.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), false))
                    {
                        return true;
                    }
                }

                return false;
            }

            bool TryCreateReplacement(ServiceDescriptor descriptor, out ServiceDescriptor replacement)
            {
                if (!HasPreferredCtor(descriptor.ImplementationType))
                {
                    replacement = null;
                    return false;
                }

                logger.LogInformation("Shimming DI constructor for {ImplementationType}.", descriptor.ImplementationType);
                ObjectFactory factory = ActivatorUtilities.CreateFactory(descriptor.ImplementationType, Type.EmptyTypes);

                replacement = ServiceDescriptor.Describe(
                    descriptor.ServiceType, sp => factory.Invoke(sp, Type.EmptyTypes), descriptor.Lifetime);
                return true;
            }

            // NetheriteProviderFactory uses ActivatorUtilitiesConstructorAttribute. We will replace this implementation with an explicit delegate.
            Type netheriteProviderFactory = Type.GetType("DurableTask.Netherite.AzureFunctions.NetheriteProviderFactory, DurableTask.Netherite.AzureFunctions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ef8c4135b1b4225a");
            foreach (ServiceDescriptor descriptor in services)
            {
                if (netheriteProviderFactory is not null
                    && descriptor.ImplementationType == netheriteProviderFactory
                    && TryCreateReplacement(descriptor, out ServiceDescriptor replacement))
                {
                    toReplace ??= new Dictionary<ServiceDescriptor, ServiceDescriptor>();
                    toReplace.Add(descriptor, replacement);
                }
            }

            if (toReplace is null)
            {
                return;
            }

            foreach ((ServiceDescriptor key, ServiceDescriptor value) in toReplace)
            {
                services.Remove(key);
                services.Add(value);
            }
        }