public void IncorrectStartMode()
        {
            const string SeedXml = "<service>"
                                   + "<id>service.exe</id>"
                                   + "<name>Service</name>"
                                   + "<description>The service.</description>"
                                   + "<executable>node.exe</executable>"
                                   + "<arguments>My Arguments</arguments>"
                                   + "<startmode>rotate</startmode>"
                                   + "<logmode>rotate</logmode>"
                                   + "<serviceaccount>"
                                   + "<domain>" + Domain + "</domain>"
                                   + "<user>" + Username + "</user>"
                                   + "<password>" + Password + "</password>"
                                   + "<allowservicelogon>" + AllowServiceAccountLogonRight + "</allowservicelogon>"
                                   + "</serviceaccount>"
                                   + "<workingdirectory>"
                                   + ExpectedWorkingDirectory
                                   + "</workingdirectory>"
                                   + @"<logpath>C:\logs</logpath>"
                                   + "</service>";

            _extendedServiceDescriptor = ServiceDescriptor.FromXML(SeedXml);
            Assert.That(_extendedServiceDescriptor.StartMode, Is.EqualTo(StartMode.Manual));
        }
Exemplo n.º 2
0
 internal MethodDescriptor(MethodDescriptorProto proto, FileDescriptor file,
                           ServiceDescriptor parent, int index)
     : base(file, parent.FullName + "." + proto.Name, index)
 {
     this.proto = proto;
     service = parent;
     file.DescriptorPool.AddSymbol(this);
 }
        public IService GetService(Type closedServiceType)
        {
            Type[] genericArguments = closedServiceType.GetTypeInfo().GenericTypeArguments;
            Type closedImplementationType =
                _descriptor.ImplementationType.MakeGenericType(genericArguments);

            var closedServiceDescriptor = new ServiceDescriptor(closedServiceType, closedImplementationType, Lifetime);
            return new Service(closedServiceDescriptor);
        }
        private static Lazy<object> GetLazyForService(IServiceProvider services, ServiceDescriptor descriptor)
        {
            CryptoUtil.Assert(descriptor != null && descriptor.Lifetime == ServiceLifetime.Singleton, "Descriptor must represent singleton.");
            CryptoUtil.Assert(descriptor.ImplementationFactory != null, "Descriptor must have an implementation factory.");

            // pull the factory out so we don't close over the whole descriptor instance
            Func<IServiceProvider, object> wrapped = descriptor.ImplementationFactory;
            return new Lazy<object>(() => wrapped(services));
        }
 public override void Configure(ServiceDescriptor descriptor, XmlNode node)
 {
     // We expect the upper logic to process any errors
     // TODO: a better parser API for types would be useful
     Pidfile = XmlHelper.SingleElement(node, "pidfile", false);
     StopTimeout = TimeSpan.FromMilliseconds(Int32.Parse(XmlHelper.SingleElement(node, "stopTimeout", false)));
     StopParentProcessFirst = Boolean.Parse(XmlHelper.SingleElement(node, "stopParentFirst", false));
     ServiceId = descriptor.Id;
 }
Exemplo n.º 6
0
        public void CanRegisterGenericService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IList<>), typeof(List<>), ServiceLifetime.Scoped);
            builder.Populate(new ServiceDescriptor[] { descriptor });
            var container = builder.Build();

            container.AssertRegistered<IList<IService>>();
        }
Exemplo n.º 7
0
        public void CanRegisterFactoryService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IService), sp => new Service(), ServiceLifetime.Transient);
            builder.Populate(new ServiceDescriptor[] { descriptor });
            var container = builder.Build();

            container.AssertRegistered<Func<IServiceProvider, IService>>();
        }
Exemplo n.º 8
0
        public void CanRegisterScopedService()
        {
            var builder = new ContainerBuilder();
            var descriptor = new ServiceDescriptor(typeof(IService), typeof(Service), ServiceLifetime.Scoped);
            builder.Populate(new ServiceDescriptor[] { descriptor });
            var container = builder.Build();

            container.AssertLifetime<IService, CurrentScopeLifetime>();
            container.AssertSharing<IService>(InstanceSharing.Shared);
            container.AssertOwnership<IService>(InstanceOwnership.OwnedByLifetimeScope);
        }
        public DefaultKeyServices(IServiceProvider services, ServiceDescriptor keyEncryptorDescriptor, ServiceDescriptor keyRepositoryDescriptor)
        {
            if (keyEncryptorDescriptor != null)
            {
                // optional
                CryptoUtil.Assert(keyEncryptorDescriptor.ServiceType == typeof(IXmlEncryptor), "Bad service type.");
                _keyEncryptorLazy = GetLazyForService(services, keyEncryptorDescriptor);
            }

            CryptoUtil.Assert(keyRepositoryDescriptor.ServiceType == typeof(IXmlRepository), "Bad service type.");
            _keyRepositoryLazy = GetLazyForService(services, keyRepositoryDescriptor);
        }
Exemplo n.º 10
0
        public void CreateCallSite_CreatesInstanceCallSite_IfTypeHasDefaultOrPublicParameterlessConstructor(Type type)
        {
            // Arrange
            var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient);
            var service = new Service(descriptor);
            var serviceProvider = new ServiceProvider(new[] { descriptor });

            // Act
            var callSite = service.CreateCallSite(serviceProvider, new HashSet<Type>());

            // Assert
            Assert.IsType<CreateInstanceCallSite>(callSite);
        }
        public void Add_AddsDescriptorToServiceDescriptors()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            var descriptor = new ServiceDescriptor(typeof(IFakeService), new FakeService());

            // Act
            serviceCollection.Add(descriptor);

            // Assert
            var result = Assert.Single(serviceCollection);
            Assert.Same(result, descriptor);
        }
Exemplo n.º 12
0
        public void CreateCallSite_Throws_IfTypeHasNoPublicConstructors()
        {
            // Arrange
            var type = typeof(TypeWithNoPublicConstructors);
            var expectedMessage = $"A suitable constructor for type '{type}' could not be located. " +
                "Ensure the type is concrete and services are registered for all parameters of a public constructor.";
            var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient);
            var service = new Service(descriptor);
            var serviceProvider = new ServiceProvider(new[] { descriptor });

            // Act and Assert
            var ex = Assert.Throws<InvalidOperationException>(() => service.CreateCallSite(serviceProvider, new HashSet<Type>()));
            Assert.Equal(expectedMessage, ex.Message);
        }
Exemplo n.º 13
0
        public void CreateCallSite_UsesNullaryConstructorIfServicesCannotBeInjectedIntoOtherConstructors()
        {
            // Arrange
            var type = typeof(TypeWithParameterizedAndNullaryConstructor);
            var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient);
            var service = new Service(descriptor);
            var serviceProvider = new ServiceProvider(new[] { descriptor });

            // Act
            var callSite = service.CreateCallSite(serviceProvider, new HashSet<Type>());

            // Assert
            Assert.IsType<CreateInstanceCallSite>(callSite);
        }
Exemplo n.º 14
0
        public void ConfigureServices(IServiceCollection services)
        {
         
         var serviceDescription = new ServiceDescriptor(typeof(IPluginService),typeof(WelcomePlugin),ServiceLifetime.Transient);

            services
                .AddMvcCore()
                .AddAuthorization()
                .AddFormatterMappings(m => m.SetMediaTypeMappingForFormat("js", new MediaTypeHeaderValue("application/json")))
                .AddJsonFormatters(j => j.Formatting = Formatting.Indented)
                .Services.Add(serviceDescription);
            
            
        }
        public void Add_AddsMultipleDescriptorToServiceDescriptors()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService());
            var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient);

            // Act
            serviceCollection.Add(descriptor1);
            serviceCollection.Add(descriptor2);

            // Assert
            Assert.Equal(2, serviceCollection.Count);
            Assert.Equal(new[] { descriptor1, descriptor2 }, serviceCollection);
        }
Exemplo n.º 16
0
 public override void Configure(ServiceDescriptor descriptor, XmlNode node)
 {
     var nodes = XmlHelper.SingleNode(node, "mapping", false).SelectNodes("map");
     if (nodes != null)
     {
         foreach (XmlNode mapNode in nodes)
         {
             var mapElement = mapNode as XmlElement;
             if (mapElement != null)
             {
                 var config = SharedDirectoryMapperConfig.FromXml(mapElement);
                 _entries.Add(config);
             }
         }
     }
 }
        public void ServiceDescriptors_AllowsRemovingPreviousRegisteredServices()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();
            var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService());
            var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient);

            // Act
            serviceCollection.Add(descriptor1);
            serviceCollection.Add(descriptor2);
            serviceCollection.Remove(descriptor1);

            // Assert
            var result = Assert.Single(serviceCollection);
            Assert.Same(result, descriptor2);
        }
Exemplo n.º 18
0
        public void CreateCallSite_CreatesConstructorCallSite_IfTypeHasConstructorWithInjectableParameters(Type type)
        {
            // Arrange
            var descriptor = new ServiceDescriptor(type, type, ServiceLifetime.Transient);
            var service = new Service(descriptor);
            var serviceProvider = GetServiceProvider(
                descriptor,
                new ServiceDescriptor(typeof(IFakeService), new FakeService())
            );

            // Act
            var callSite = service.CreateCallSite(serviceProvider, new HashSet<Type>());

            // Assert
            var constructorCallSite = Assert.IsType<ConstructorCallSite>(callSite);
            Assert.Equal(new[] { typeof(IFakeService) }, GetParameters(constructorCallSite));
        }
Exemplo n.º 19
0
        private static void WireUpDbContexts(IServiceCollection services, IConfiguration configuration)
        {
            var cmsConnString = configuration["Data:cmsconnection:ConnectionString"];
            var authConnString = configuration["Data:authconnection:ConnectionString"];

            var connectionStrings = new Dictionary<Type, string>
            {
                {typeof (AuthDbContext), authConnString},
                {typeof (ElmahDbContext), cmsConnString},
                {typeof (ComponentsDbContext), cmsConnString}
            };

            var serviceDescriptor = new ServiceDescriptor(typeof(IDbContextFactory), new DbContextFactory(connectionStrings));
            services.Add(serviceDescriptor);

            services.AddSingleton<IDbContextScopeFactory, DbContextScopeFactory>();
            services.AddSingleton<IAmbientDbContextLocator, AmbientDbContextLocator>();
        }
        /// <summary>
        /// This module looks for any method of IShapeTableProvider implementations
        /// that has the <see cref="ShapeAttribute"/>.
        /// </summary>
        public void Configure(IServiceCollection serviceCollection)
        {
            // Register custom tag helper descriptor
            serviceCollection.AddTransient<IMvcRazorHost, TagHelperMvcRazorHost>();

            // Copy the collection as we are about to change it
            ServiceDescriptor[] serviceDescriptors = new ServiceDescriptor[serviceCollection.Count];
            serviceCollection.CopyTo(serviceDescriptors, 0);

            foreach (var serviceDescriptor in serviceDescriptors)
            {
                var serviceType = serviceDescriptor.ImplementationType;

                if (serviceType == null || !typeof(IShapeTableProvider).IsAssignableFrom(serviceType))
                {
                    continue;
                }

                bool hasShapes = false;
                foreach (var method in serviceType.GetMethods())
                {
                    var customAttributes = method.GetCustomAttributes(typeof(ShapeAttribute), false).OfType<ShapeAttribute>();
                    foreach (var customAttribute in customAttributes)
                    {
                        hasShapes = true;
                        // PERF: Analyze the impact of an important number of instances
                        // in the service collection
                        serviceCollection.AddInstance(
                            new ShapeAttributeOccurrence(customAttribute,
                            method,
                            serviceType));
                    }
                }

                // If the type was registered using IDependency, we need to
                // register it itself or the invocation won't be able
                // to be done on the correct instance as the default ASP.NET DI
                // won't resolve a type explicitely
                if (hasShapes && serviceDescriptor.ImplementationInstance == null)
                {
                    serviceCollection.AddScoped(serviceType);
                }
            }
        }
Exemplo n.º 21
0
        public void Populate(IServiceCollection services)
        {
            foreach (var type in Types)
            {
                var typeInfo = type.GetTypeInfo();

                var attribute = typeInfo.GetCustomAttribute<ServiceDescriptorAttribute>();

                if (attribute == null)
                {
                    continue;
                }

                var serviceType = attribute.ServiceType ?? type;

                var descriptor = new ServiceDescriptor(serviceType, type, attribute.Lifetime);

                services.Add(descriptor);
            }
        }
        private TestServer CreateServer(IWebpackService webpackService)
        {
            var mockServiceDescriptor = new ServiceDescriptor(typeof(IWebpackService), webpackService);

            var builder = new WebHostBuilder()
               .Configure(app =>
                       {
                           app.UseWebpackDevServer();
                           app.Run(async context =>
                           {
                               await context.Response.WriteAsync(DEFAULT_RESPONSE);
                           });
                       })
               .ConfigureServices(services =>
                       {
                           services.AddLogging();
                           services.Add(mockServiceDescriptor);
                       });
            return new TestServer(builder);
        }
Exemplo n.º 23
0
        public void BuiltExpressionWillReturnResolvedServiceWhenAppropriate(
            ServiceDescriptor[] desciptors, Type serviceType, Func<object, object, bool> compare)
        {
            var provider = new ServiceProvider(desciptors);

            var callSite = provider.GetServiceCallSite(serviceType, new HashSet<Type>());
            var collectionCallSite = provider.GetServiceCallSite(typeof(IEnumerable<>).MakeGenericType(serviceType), new HashSet<Type>());

            var compiledCallSite = CompileCallSite(callSite);
            var compiledCollectionCallSite = CompileCallSite(collectionCallSite);

            var service1 = callSite.Invoke(provider);
            var service2 = compiledCallSite(provider);
            var serviceEnumerator = ((IEnumerable)compiledCollectionCallSite(provider)).GetEnumerator();

            Assert.NotNull(service1);
            Assert.True(compare(service1, service2));

            // Service can be IEnumerable resolved. The IEnumerable should have exactly one element.
            Assert.True(serviceEnumerator.MoveNext());
            Assert.True(compare(service1, serviceEnumerator.Current));
            Assert.False(serviceEnumerator.MoveNext());
        }
        private void Register(ServiceDescriptor descriptor)
        {
            if (descriptor.ImplementationType != null)
            {
                For(descriptor.ServiceType)
                    .LifecycleIs(descriptor.Lifetime)
                    .Use(descriptor.ImplementationType);

                return;
            }

            if (descriptor.ImplementationFactory != null)
            {
                For(descriptor.ServiceType)
                    .LifecycleIs(descriptor.Lifetime)
                    .Use(CreateFactory(descriptor));

                return;
            }

            For(descriptor.ServiceType)
                .LifecycleIs(descriptor.Lifetime)
                .Use(descriptor.ImplementationInstance);
        }
        private static void Register(this IProfileRegistry registry, ServiceDescriptor descriptor)
        {
            if (descriptor.ImplementationType != null)
            {
                registry.For(descriptor.ServiceType)
                    .LifecycleIs(descriptor.Lifetime)
                    .Use(descriptor.ImplementationType);

                return;
            }

            if (descriptor.ImplementationFactory != null)
            {
                registry.For(descriptor.ServiceType)
                    .LifecycleIs(descriptor.Lifetime)
                    .Use(descriptor.CreateFactory());

                return;
            }

            registry.For(descriptor.ServiceType)
                .LifecycleIs(descriptor.Lifetime)
                .Use(descriptor.ImplementationInstance);
        }
 static ServiceDescriptor Creator(Type baseType, Type messageType, Type implementationType) =>
 ServiceDescriptor.Singleton(typeof(IRuleEngine <>).MakeGenericType(messageType), typeof(FluentHybridRuleEngine <>).MakeGenericType(messageType));
 public InstanceService(ServiceDescriptor descriptor)
 {
     _descriptor = descriptor;
 }
Exemplo n.º 28
0
 public TenantBuilder WithResolutionStrategy <T>(ServiceLifetime lifetime = ServiceLifetime.Transient) where T : class, ITenantResolutionStrategy
 {
     _services.Add(ServiceDescriptor.Describe(typeof(ITenantResolutionStrategy), typeof(T), lifetime));
     return(this);
 }
Exemplo n.º 29
0
 protected override void AfterAddApplication(IServiceCollection services)
 {
     _auditingStore = Substitute.For <IAuditingStore>();
     services.Replace(ServiceDescriptor.Singleton(_auditingStore));
 }
Exemplo n.º 30
0
 public static ILoggingBuilder UseLoggerSetup(this ILoggingBuilder builder, string log4NetConfigFile = "log4net.config")
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <ILoggerProvider>(new Log4NetProvider(log4NetConfigFile)));
     return(builder);
 }
Exemplo n.º 31
0
 private static string GetCacheKey(ServiceDescriptor descriptor)
 {
     return(descriptor.Id);
 }
 public virtual void AddNewDescriptor([NotNull] IList <int> indexes, [NotNull] ServiceDescriptor newDescriptor)
 {
     indexes.Add(ServiceCollection.Count);
     ServiceCollection.Add(newDescriptor);
 }
Exemplo n.º 33
0
 private static void AddAbpIdentityOptionsFactory(IServiceCollection services)
 {
     services.Replace(ServiceDescriptor.Transient <IOptionsFactory <IdentityOptions>, AbpIdentityOptionsFactory>());
     services.Replace(ServiceDescriptor.Scoped <IOptions <IdentityOptions>, OptionsManager <IdentityOptions> >());
 }
Exemplo n.º 34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>());
            services.AddMvc().AddJsonOptions(options =>
            {
                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                options.SerializerSettings.Converters.Add(
                    new Newtonsoft.Json.Converters.IsoDateTimeConverter()
                {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                }
                    );
                //小写
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //   //  options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            });
            //   services.AddMvc().AddXmlSerializerFormatters();
            //  services.AddMvc().AddXmlDataContractSerializerFormatters();
            services.AddLogging();
            services.AddCors(options =>
                             options.AddPolicy("AllowSameDomain", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
                                               ));
            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSameDomain"));
            });

            #region Swagger

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "接口文档",
                    Description    = "接口文档-基础",
                    TermsOfService = "https://example.com/terms",
                    Contact        = new Contact
                    {
                        Name  = "XXX1111",
                        Email = "*****@*****.**",
                        Url   = "https://example.com/terms"
                    }
                    ,
                    License = new License
                    {
                        Name = "Use under LICX",
                        Url  = "https://example.com/license",
                    }
                });

                c.SwaggerDoc("v2", new Info
                {
                    Version        = "v2",
                    Title          = "接口文档",
                    Description    = "接口文档-基础",
                    TermsOfService = "https://example.com/terms",
                    Contact        = new Contact
                    {
                        Name  = "XXX2222",
                        Email = "*****@*****.**",
                        Url   = "https://example.com/terms"
                    }
                    ,
                    License = new License
                    {
                        Name = "Use under LICX",
                        Url  = "https://example.com/license",
                    }
                });
                c.OperationFilter <HttpHeaderOperationFilter>();
                c.DocumentFilter <HiddenApiFilter>();
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"CompanyName.ProjectName.ICommonServer.xml"));
            });

            #endregion Swagger

            #region MiniProfiler

            if (bool.Parse(Configuration["IsUseMiniProfiler"]))
            {
                //https://www.cnblogs.com/lwqlun/p/10222505.html
                services.AddMiniProfiler(options =>
                                         options.RouteBasePath = "/profiler"
                                         ).AddEntityFramework();
            }

            #endregion MiniProfiler

            services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"]));
            var container = AutofacExt.InitAutofac(services, Assembly.GetExecutingAssembly());
            return(new AutofacServiceProvider(container));
        }
Exemplo n.º 35
0
 public bool MatchesActual(
         ServiceDescriptor actual)
     => ((actual.ImplementationFactory is null) == (ImplementationFactoryServiceType is null))
Exemplo n.º 36
0
        private ServiceCallSite?TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain)
        {
            ServiceCacheKey callSiteKey = new ServiceCacheKey(serviceType, DefaultSlot);

            if (_callSiteCache.TryGetValue(callSiteKey, out ServiceCallSite? serviceCallSite))
            {
                return(serviceCallSite);
            }

            try
            {
                callSiteChain.Add(serviceType);

                if (serviceType.IsConstructedGenericType &&
                    serviceType.GetGenericTypeDefinition() == typeof(IEnumerable <>))
                {
                    Type itemType = serviceType.GenericTypeArguments[0];
                    CallSiteResultCacheLocation cacheLocation = CallSiteResultCacheLocation.Root;

                    var callSites = new List <ServiceCallSite>();

                    // If item type is not generic we can safely use descriptor cache
                    if (!itemType.IsConstructedGenericType &&
                        _descriptorLookup.TryGetValue(itemType, out ServiceDescriptorCacheItem descriptors))
                    {
                        for (int i = 0; i < descriptors.Count; i++)
                        {
                            ServiceDescriptor descriptor = descriptors[i];

                            // Last service should get slot 0
                            int slot = descriptors.Count - i - 1;
                            // There may not be any open generics here
                            ServiceCallSite?callSite = TryCreateExact(descriptor, itemType, callSiteChain, slot);
                            Debug.Assert(callSite != null);

                            cacheLocation = GetCommonCacheLocation(cacheLocation, callSite.Cache.Location);
                            callSites.Add(callSite);
                        }
                    }
                    else
                    {
                        int slot = 0;
                        // We are going in reverse so the last service in descriptor list gets slot 0
                        for (int i = _descriptors.Length - 1; i >= 0; i--)
                        {
                            ServiceDescriptor descriptor = _descriptors[i];
                            ServiceCallSite?  callSite   = TryCreateExact(descriptor, itemType, callSiteChain, slot) ??
                                                           TryCreateOpenGeneric(descriptor, itemType, callSiteChain, slot, false);

                            if (callSite != null)
                            {
                                slot++;

                                cacheLocation = GetCommonCacheLocation(cacheLocation, callSite.Cache.Location);
                                callSites.Add(callSite);
                            }
                        }

                        callSites.Reverse();
                    }


                    ResultCache resultCache = ResultCache.None;
                    if (cacheLocation == CallSiteResultCacheLocation.Scope || cacheLocation == CallSiteResultCacheLocation.Root)
                    {
                        resultCache = new ResultCache(cacheLocation, callSiteKey);
                    }

                    return(_callSiteCache[callSiteKey] = new IEnumerableCallSite(resultCache, itemType, callSites.ToArray()));
                }

                return(null);
            }
            finally
            {
                callSiteChain.Remove(serviceType);
            }
        }
 private static Expression<Func<IContext, object>> CreateFactory(ServiceDescriptor descriptor)
 {
     return context => descriptor.ImplementationFactory(context.GetInstance<IServiceProvider>());
 }
Exemplo n.º 38
0
 /// <summary>
 /// Substitui um serviço por uma instância de mock
 /// </summary>
 /// <typeparam name="T">Tipo do serviço a ser substituído</typeparam>
 /// <param name="serviceCollection">Coleção de serviços da aplicação</param>
 /// <param name="originalService">Descritor do serviço original</param>
 /// <param name="mockService">Mock do serviço original</param>
 private void SwapService <T>(IServiceCollection serviceCollection, ServiceDescriptor originalService, Mock <T> mockService) where T : class
 {
     serviceCollection.Remove(originalService);
     serviceCollection.Add(new ServiceDescriptor(originalService.ServiceType, mockService.Object));
 }
Exemplo n.º 39
0
 /// <summary>
 /// Replaces multiple services in the <see cref="IServiceCollection"/>.
 /// </summary>
 /// <param name="serviceCollection">Instance of <see cref="IServiceCollection"/> type.</param>
 /// <param name="descriptor"><see cref="ServiceDescriptor"/> providing the services.</param>
 public static void ReplaceEnumerable(this IServiceCollection serviceCollection, ServiceDescriptor descriptor)
 {
     CommonValidator.CheckForNullReference(descriptor, nameof(descriptor));
     RemoveServices(serviceCollection, s => s.ServiceType == descriptor.ServiceType && s.Lifetime == descriptor.Lifetime);
     serviceCollection.TryAddEnumerable(descriptor);
 }
Exemplo n.º 40
0
 /// <summary>
 /// Indicates that settings for <typeparamref name="TProvider"/> should be loaded into <typeparamref name="TOptions"/> type.
 /// </summary>
 /// <typeparam name="TOptions">The options class </typeparam>
 /// <typeparam name="TProvider">The provider class</typeparam>
 public static void RegisterProviderOptions <TOptions, TProvider>(this IServiceCollection services) where TOptions : class
 {
     services.TryAddEnumerable(ServiceDescriptor.Singleton <IConfigureOptions <TOptions>, LoggerProviderConfigureOptions <TOptions, TProvider> >());
     services.TryAddEnumerable(ServiceDescriptor.Singleton <IOptionsChangeTokenSource <TOptions>, LoggerProviderOptionsChangeTokenSource <TOptions, TProvider> >());
 }
Exemplo n.º 41
0
 public static void AddDNTAuditingStore <TDbContext>(this IServiceCollection services)
     where TDbContext : DbContext
 {
     services.Replace(ServiceDescriptor.Transient(typeof(IAuditingStore), typeof(AuditLogStore <TDbContext>)));
 }
 /// <summary>
 /// 应用标记。
 /// </summary>
 /// <param name="descriptor">服务描述符。</param>
 public abstract void Apply(ServiceDescriptor descriptor);
Exemplo n.º 43
0
        public static IHostBuilder AddScriptHostCore(this IHostBuilder builder, ScriptApplicationHostOptions applicationHostOptions, Action <IWebJobsBuilder> configureWebJobs = null)
        {
            var skipHostInitialization = builder.Properties.ContainsKey(ScriptConstants.SkipHostInitializationKey);

            builder.ConfigureWebJobs(webJobsBuilder =>
            {
                // Built in binding registrations
                webJobsBuilder.AddExecutionContextBinding(o =>
                {
                    o.AppDirectory = applicationHostOptions.ScriptPath;
                })
                .AddHttp(o =>
                {
                    o.SetResponse = HttpBinding.SetResponse;
                })
                .AddTimers()
                .AddManualTrigger();

                if (!skipHostInitialization)
                {
                    // Only set our external startup if we're not suppressing host initialization
                    // as we don't want to load user assemblies otherwise.
                    webJobsBuilder.UseScriptExternalStartup(applicationHostOptions.ScriptPath);
                }

                configureWebJobs?.Invoke(webJobsBuilder);
            }, o => o.AllowPartialHostStartup = true);

            // Script host services - these services are scoped to a host instance, and when a new host
            // is created, these services are recreated
            builder.ConfigureServices(services =>
            {
                // Core WebJobs/Script Host services
                services.AddSingleton <ScriptHost>();
                services.AddSingleton <IScriptJobHost>(p => p.GetRequiredService <ScriptHost>());
                services.AddSingleton <IJobHost>(p => p.GetRequiredService <ScriptHost>());
                services.AddSingleton <IFunctionMetadataManager, FunctionMetadataManager>();
                services.AddSingleton <IProxyMetadataManager, ProxyMetadataManager>();
                services.AddSingleton <ITypeLocator, ScriptTypeLocator>();
                services.AddSingleton <ScriptSettingsManager>();
                services.AddTransient <IExtensionsManager, ExtensionsManager>();
                services.TryAddSingleton <IMetricsLogger, MetricsLogger>();
                services.TryAddSingleton <IScriptJobHostEnvironment, ConsoleScriptJobHostEnvironment>();

                // Script binding providers
                services.TryAddEnumerable(ServiceDescriptor.Singleton <IScriptBindingProvider, WebJobsCoreScriptBindingProvider>());
                services.TryAddEnumerable(ServiceDescriptor.Singleton <IScriptBindingProvider, CoreExtensionsScriptBindingProvider>());
                services.TryAddEnumerable(ServiceDescriptor.Singleton <IScriptBindingProvider, GeneralScriptBindingProvider>());

                // Configuration
                services.AddSingleton <IOptions <ScriptApplicationHostOptions> >(new OptionsWrapper <ScriptApplicationHostOptions>(applicationHostOptions));
                services.AddSingleton <IOptionsMonitor <ScriptApplicationHostOptions> >(new ScriptApplicationHostOptionsMonitor(applicationHostOptions));
                services.ConfigureOptions <ScriptHostOptionsSetup>();
                services.ConfigureOptions <JobHostFunctionTimeoutOptionsSetup>();
                // TODO: pgopa only add this to WebHostServiceCollection
                services.ConfigureOptions <LanguageWorkerOptionsSetup>();
                services.AddOptions <FunctionResultAggregatorOptions>()
                .Configure <IConfiguration>((o, c) =>
                {
                    c.GetSection(ConfigurationSectionNames.JobHost)
                    .GetSection(ConfigurationSectionNames.Aggregator)
                    .Bind(o);
                });

                services.AddSingleton <IFileLoggingStatusManager, FileLoggingStatusManager>();
                services.AddSingleton <IPrimaryHostStateProvider, PrimaryHostStateProvider>();

                if (!applicationHostOptions.HasParentScope)
                {
                    AddCommonServices(services);
                }

                // Hosted services
                services.TryAddEnumerable(ServiceDescriptor.Singleton <IHostedService, PrimaryHostCoordinator>());
            });

            return(builder);
        }
Exemplo n.º 44
0
        public void HandleRequests()
        {
            IEnumerator <ISyncRequest> requests       = syncRequests.GetEnumerator();
            ICollection <ISyncRequest> removeRequests = new List <ISyncRequest>();

            while (requests.MoveNext())
            {
                ISyncRequest syncRequest = requests.Current;

                /*
                 * Fire Sync Started Event
                 */
                ISyncEvents syncEventHandler = resourceManager.GetSyncEventHandler();
                if (syncEventHandler != null)
                {
                    syncEventHandler.OnStart(syncRequest);
                }


                /*
                 * Process Request
                 */
                SyncDescriptor refreshDescriptor = resourceManager.GetSyncDescriptor(syncRequest.GetName());

                IEnumerator <String> services = refreshDescriptor.GetServiceDescriptorNames();
                while (services.MoveNext())
                {
                    String service = services.Current;

                    String serviceName = service.Substring(0, service.IndexOf(Constants.SYNC_DESCRIPTOR_SERVICE_SEPARATOR));
                    String requestName = service.Substring(service.IndexOf(Constants.SYNC_DESCRIPTOR_SERVICE_SEPARATOR) + 1, service.Length - (service.IndexOf(Constants.SYNC_DESCRIPTOR_SERVICE_SEPARATOR) + 1));


                    ServiceDescriptor         serviceDescriptor = resourceManager.RequiredServiceDescriptorBasedOnName(serviceName);
                    ServiceDescriptor.Request api = serviceDescriptor.GetRequest(requestName);

                    String apiHandler = api.GetHandler();

                    IService serviceHandler = (IService)ClassUtils.CreateClassInstance(apiHandler);
                    serviceHandler.SetServiceDescriptor(serviceDescriptor);

                    IEnumerator <String> resources = syncRequest.GetResources();
                    while (resources.MoveNext())
                    {
                        String resourceName  = resources.Current;
                        Object resourceValue = syncRequest.GetResource(resourceName);

                        serviceHandler.AddResource(resourceName, resourceValue);
                    }


                    serviceHandler.Invoke();
                }


                /*
                 * Fire Sync Started Event
                 */
                if (syncEventHandler != null)
                {
                    syncEventHandler.OnFinish(syncRequest);
                }


                removeRequests.Add(syncRequest);
            }

            foreach (ISyncRequest removeRequest in removeRequests)
            {
                syncRequests.Remove(removeRequest);
            }

            syncWorkerThread = null;
        }
Exemplo n.º 45
0
 public override void ConfigureServices(ServiceConfigurationContext context)
 {
     context.Services.Replace(ServiceDescriptor.Transient <IComponentActivator, ServiceProviderComponentActivator>());
 }
Exemplo n.º 46
0
 public virtual void Configure(ServiceDescriptor descriptor, XmlNode node, IEventWriter logger)
 {
     // Do nothing
 }
Exemplo n.º 47
0
 public TenantBuilder WithStore <T>(ServiceLifetime lifetime = ServiceLifetime.Transient) where T : class, ITenantStore
 {
     _services.Add(ServiceDescriptor.Describe(typeof(ITenantStore), typeof(T), lifetime));
     return(this);
 }
Exemplo n.º 48
0
        public static IHostBuilder AddWebScriptHost(this IHostBuilder builder, IServiceProvider rootServiceProvider,
                                                    IServiceScopeFactory rootScopeFactory, ScriptApplicationHostOptions webHostOptions, Action <IWebJobsBuilder> configureWebJobs = null)
        {
            ILoggerFactory       configLoggerFactory = rootServiceProvider.GetService <ILoggerFactory>();
            IDependencyValidator validator           = rootServiceProvider.GetService <IDependencyValidator>();

            builder.UseServiceProviderFactory(new JobHostScopedServiceProviderFactory(rootServiceProvider, rootScopeFactory, validator))
            .ConfigureServices(services =>
            {
                // register default configuration
                // must happen before the script host is added below
                services.ConfigureOptions <HttpOptionsSetup>();
            })
            .AddScriptHost(webHostOptions, configLoggerFactory, webJobsBuilder =>
            {
                webJobsBuilder
                .AddAzureStorageCoreServices();

                configureWebJobs?.Invoke(webJobsBuilder);

                ConfigureRegisteredBuilders(webJobsBuilder, rootServiceProvider);
            })
            .ConfigureAppConfiguration(configurationBuilder =>
            {
                ConfigureRegisteredBuilders(configurationBuilder, rootServiceProvider);
            })
            .ConfigureLogging(loggingBuilder =>
            {
                loggingBuilder.Services.AddSingleton <ILoggerFactory, ScriptLoggerFactory>();

                loggingBuilder.AddWebJobsSystem <SystemLoggerProvider>();
                loggingBuilder.Services.AddSingleton <ILoggerProvider, UserLogMetricsLoggerProvider>();
                loggingBuilder.Services.AddSingleton <ILoggerProvider, AzureMonitorDiagnosticLoggerProvider>();

                ConfigureRegisteredBuilders(loggingBuilder, rootServiceProvider);
            })
            .ConfigureServices(services =>
            {
                var webHostEnvironment = rootServiceProvider.GetService <IScriptWebHostEnvironment>();
                var environment        = rootServiceProvider.GetService <IEnvironment>();
                if (FunctionsSyncManager.IsSyncTriggersEnvironment(webHostEnvironment, environment))
                {
                    services.AddSingleton <IHostedService, FunctionsSyncService>();
                }

                services.AddSingleton <HttpRequestQueue>();
                services.AddSingleton <IHostLifetime, JobHostHostLifetime>();
                services.TryAddSingleton <IWebJobsExceptionHandler, WebScriptHostExceptionHandler>();
                services.AddSingleton <IScriptJobHostEnvironment, WebScriptJobHostEnvironment>();

                services.AddSingleton <DefaultScriptWebHookProvider>();
                services.TryAddSingleton <IScriptWebHookProvider>(p => p.GetService <DefaultScriptWebHookProvider>());
                services.TryAddSingleton <IWebHookProvider>(p => p.GetService <DefaultScriptWebHookProvider>());

                // Make sure the registered IHostIdProvider is used
                IHostIdProvider provider = rootServiceProvider.GetService <IHostIdProvider>();
                if (provider != null)
                {
                    services.AddSingleton <IHostIdProvider>(provider);
                }

                // Logging and diagnostics
                services.AddSingleton <IMetricsLogger, WebHostMetricsLogger>();
                services.AddSingleton <IEventCollectorProvider, FunctionInstanceLogCollectorProvider>();

                // Hosted services
                services.TryAddEnumerable(ServiceDescriptor.Singleton <IHostedService, HttpInitializationService>());
                services.TryAddEnumerable(ServiceDescriptor.Singleton <IHostedService, FileMonitoringService>());
            });

            var debugStateProvider = rootServiceProvider.GetService <IDebugStateProvider>();

            if (debugStateProvider.InDebugMode)
            {
                builder.UseEnvironment(EnvironmentName.Development);
            }

            return(builder);
        }
Exemplo n.º 49
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var context = builder.GetContext();

            var section = context.Configuration.GetSection("Acmebot");

            // Add Options
            builder.Services.AddOptions <AcmebotOptions>()
            .Bind(section.Exists() ? section : context.Configuration.GetSection("LetsEncrypt"))
            .ValidateDataAnnotations()
            .PostConfigure(options =>
            {
                // Backward compatibility
                if (options.Endpoint == "https://acme-v02.api.letsencrypt.org/")
                {
                    options.PreferredChain ??= "DST Root CA X3";
                }
            });

            // Add Services
            builder.Services.Replace(ServiceDescriptor.Transient(typeof(IOptionsFactory <>), typeof(OptionsFactory <>)));

            builder.Services.AddHttpClient();

            builder.Services.AddSingleton <ITelemetryInitializer, ApplicationVersionInitializer <Startup> >();

            builder.Services.AddSingleton(new LookupClient(new LookupClientOptions(NameServer.GooglePublicDns, NameServer.GooglePublicDns2)
            {
                UseCache            = false,
                UseRandomNameServer = true
            }));

            builder.Services.AddSingleton(provider =>
            {
                var options = provider.GetRequiredService <IOptions <AcmebotOptions> >();

                return(AzureEnvironment.Get(options.Value.Environment));
            });

            builder.Services.AddSingleton(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >();
                var environment = provider.GetRequiredService <AzureEnvironment>();

                var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
                {
                    AuthorityHost = environment.ActiveDirectory
                });

                return(new CertificateClient(new Uri(options.Value.VaultBaseUrl), credential));
            });

            builder.Services.AddSingleton <AcmeProtocolClientFactory>();

            builder.Services.AddSingleton <WebhookInvoker>();
            builder.Services.AddSingleton <ILifeCycleNotificationHelper, WebhookLifeCycleNotification>();

            builder.Services.AddSingleton <IDnsProvider>(provider =>
            {
                var options     = provider.GetRequiredService <IOptions <AcmebotOptions> >().Value;
                var environment = provider.GetRequiredService <AzureEnvironment>();

                // Provider should be in alphabetical order
                if (options.AzureDns != null)
                {
                    return(new AzureDnsProvider(options.AzureDns, environment));
                }

                if (options.Cloudflare != null)
                {
                    return(new CloudflareProvider(options.Cloudflare));
                }

                if (options.DnsMadeEasy != null)
                {
                    return(new DnsMadeEasyProvider(options.DnsMadeEasy));
                }

                if (options.Google != null)
                {
                    return(new GoogleDnsProvider(options.Google));
                }

                if (options.GratisDns != null)
                {
                    return(new GratisDnsProvider(options.GratisDns));
                }

                if (options.TransIp != null)
                {
                    return(new TransIpProvider(options, options.TransIp, environment));
                }

                // Backward compatibility
                if (options.SubscriptionId != null)
                {
                    return(new AzureDnsProvider(new AzureDnsOptions {
                        SubscriptionId = options.SubscriptionId
                    }, environment));
                }

                throw new NotSupportedException();
            });
        }
Exemplo n.º 50
0
 /// <summary>
 /// Adds OpenId Connect authentication to <see cref="AuthenticationBuilder"/> using the specified scheme.
 /// <para>
 /// OpenID Connect is an identity layer on top of the OAuth 2.0 protocol. It allows clients
 /// to request and receive information about authenticated sessions and end-users.
 /// </para>
 /// </summary>
 /// <param name="builder">The <see cref="AuthenticationBuilder"/>.</param>
 /// <param name="authenticationScheme">The authentication scheme.</param>
 /// <param name="displayName">A display name for the authentication handler.</param>
 /// <param name="configureOptions">A delegate to configure <see cref="OpenIdConnectOptions"/>.</param>
 /// <returns>A reference to <paramref name="builder"/> after the operation has completed.</returns>
 public static AuthenticationBuilder AddOpenIdConnect(this AuthenticationBuilder builder, string authenticationScheme, string?displayName, Action <OpenIdConnectOptions> configureOptions)
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IPostConfigureOptions <OpenIdConnectOptions>, OpenIdConnectPostConfigureOptions>());
     return(builder.AddRemoteScheme <OpenIdConnectOptions, OpenIdConnectHandler>(authenticationScheme, displayName, configureOptions));
 }
Exemplo n.º 51
0
 public ChangeEventSubscriptionState(ServiceDescriptor serviceDescriptor, CpService service, HttpWebRequest request) :
     base(request)
 {
     _serviceDescriptor = serviceDescriptor;
     _service           = service;
 }
 public static IServiceCollection AddHttpClientRequestLogging(this IServiceCollection services)
 {
     services.Replace(ServiceDescriptor.Singleton <IHttpMessageHandlerBuilderFilter, RequestLoggingFilter>());
     return(services);
 }
Exemplo n.º 53
0
 /// <summary>
 /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
 /// </summary>
 /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
 public void Add(ServiceDescriptor item)
 {
     _descriptors.Add(item);
 }
Exemplo n.º 54
0
 private static bool Contains(this IEnumerable <ServiceDescriptor> serviceDescriptors, ServiceDescriptor serviceDescriptor)
 {
     return(serviceDescriptors.Any(x => x.ImplementationType == serviceDescriptor.ImplementationType));
 }
Exemplo n.º 55
0
 /// <summary>
 /// 初始化 <see cref="ServiceContext"/> 类的新实例。
 /// </summary>
 /// <param name="configuration"></param>
 /// <param name="requestContext"></param>
 /// <param name="serviceDescriptor"></param>
 internal ServiceContext(HttpConfiguration configuration, RequestContext requestContext, ServiceDescriptor serviceDescriptor)
 {
     Configuration     = configuration;
     RequestContext    = requestContext;
     HttpContext       = requestContext.HttpContext;
     ServiceDescriptor = serviceDescriptor;
     Converters        = new List <ITextConverter>();
     Filters           = new List <FilterAttribute>();
     Converters.AddRange(configuration.Converters);
     Filters.AddRange(configuration.Filters);
 }
Exemplo n.º 56
0
 /// <summary>
 /// Replaces a service in the <see cref="IServiceCollection"/>.
 /// </summary>
 /// <param name="serviceCollection">Instance of <see cref="IServiceCollection"/> type.</param>
 /// <param name="service">Type of the service which will be replaced.</param>
 /// <param name="implementationFactory">Service implementation factory which will be used for replacement.</param>
 /// <param name="lifetime">The <see cref="ServiceLifetime"/> which will be applied on the replaced service.</param>
 /// <returns>The same <see cref="IServiceCollection"/>.</returns>
 public static IServiceCollection Replace(this IServiceCollection serviceCollection, Type service, Func <IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
 {
     serviceCollection.Remove(service).Add(ServiceDescriptor.Describe(service, implementationFactory, lifetime));
     TestServiceProvider.SaveServiceLifetime(service, lifetime);
     return(serviceCollection);
 }
Exemplo n.º 57
0
 /// <summary>
 /// 应用标记。
 /// </summary>
 /// <param name="descriptor">服务描述符。</param>
 public override void Apply(ServiceDescriptor descriptor)
 {
     descriptor.Metadatas[Name] = Data;
 }
Exemplo n.º 58
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddContext(Configuration);

            #region AddJwtBearer

            services.AddAuthentication(opts =>
            {
                opts.DefaultScheme             = CookieAuthenticationDefaults.AuthenticationScheme;
                opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opts.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath  = "/cms/oauth2/signin";
                options.LogoutPath = "/cms/oauth2/signout";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                //identityserver4 地址 也就是本项目地址
                options.Authority            = Configuration["Service:Authority"];
                options.RequireHttpsMetadata = false;
                options.Audience             = Configuration["Service:Name"];

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // The signing key must match!
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Authentication:JwtBearer:SecurityKey"])),

                    // Validate the JWT Issuer (iss) claim
                    ValidateIssuer = true,
                    ValidIssuer    = Configuration["Authentication:JwtBearer:Issuer"],

                    // Validate the JWT Audience (aud) claim
                    ValidateAudience = true,
                    ValidAudience    = Configuration["Authentication:JwtBearer:Audience"],

                    // Validate the token expiry
                    ValidateLifetime = true,

                    // If you want to allow a certain amount of clock drift, set that here
                    //ClockSkew = TimeSpan.Zero
                };

                //options.TokenValidationParameters = new TokenValidationParameters()
                //{
                //    ClockSkew = TimeSpan.Zero   //偏移设置为了0s,用于测试过期策略,完全按照access_token的过期时间策略,默认原本为5分钟
                //};


                //使用Authorize设置为需要登录时,返回json格式数据。
                options.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = context =>
                    {
                        //Token expired
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("Token-Expired", "true");
                        }

                        return(Task.CompletedTask);
                    },
                    OnChallenge = context =>
                    {
                        //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦
                        context.HandleResponse();

                        string message;
                        ErrorCode errorCode;
                        int statusCode = StatusCodes.Status401Unauthorized;

                        if (context.Error == "invalid_token" &&
                            context.ErrorDescription == "The token is expired")
                        {
                            message    = "令牌过期";
                            errorCode  = ErrorCode.TokenExpired;
                            statusCode = StatusCodes.Status422UnprocessableEntity;
                        }
                        else if (context.Error == "invalid_token" && context.ErrorDescription.IsNullOrEmpty())
                        {
                            message   = "令牌失效";
                            errorCode = ErrorCode.TokenInvalidation;
                        }

                        else
                        {
                            message   = "请先登录" + context.ErrorDescription;   //""认证失败,请检查请求头或者重新登录";
                            errorCode = ErrorCode.AuthenticationFailed;
                        }

                        context.Response.ContentType = "application/json";
                        context.Response.StatusCode  = statusCode;
                        context.Response.WriteAsync(new UnifyResponseDto(errorCode, message, context.HttpContext)
                                                    .ToString());

                        return(Task.FromResult(0));
                    }
                };
            })
            .AddGitHub(options =>
            {
                options.ClientId     = Configuration["Authentication:GitHub:ClientId"];
                options.ClientSecret = Configuration["Authentication:GitHub:ClientSecret"];
                options.Scope.Add("user:email");
                options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url");
                //登录成功后可通过  authenticateResult.Principal.FindFirst(ClaimTypes.Uri)?.Value;  得到GitHub头像
                options.ClaimActions.MapJsonKey(LinConsts.Claims.BIO, "bio");
                options.ClaimActions.MapJsonKey(LinConsts.Claims.BlogAddress, "blog");
            })
            .AddQQ(options =>
            {
                options.ClientId     = Configuration["Authentication:QQ:ClientId"];
                options.ClientSecret = Configuration["Authentication:QQ:ClientSecret"];
            });

            #endregion


            //services.AddCsRedisCore();

            services.AddAutoMapper(typeof(UserProfile).Assembly, typeof(PoemProfile).Assembly);

            services.AddCors();

            #region Mvc

            services.AddControllers(options =>
            {
                options.ValueProviderFactories.Add(new ValueProviderFactory()); //设置SnakeCase形式的QueryString参数
                options.Filters.Add <LogActionFilterAttribute>();               // 添加请求方法时的日志记录过滤器
                // options.Filters.Add<LinCmsExceptionFilter>(); // 添加请求方法时的日志记录过滤器
            })
            .AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:MM:ss";
                // 设置自定义时间戳格式
                opt.SerializerSettings.Converters = new List <JsonConverter>()
                {
                    new LinCmsTimeConverter()
                };
                // 设置下划线方式,首字母是小写
                opt.SerializerSettings.ContractResolver = new DefaultContractResolver()
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                    {
                        ProcessDictionaryKeys = true
                    }
                };
            })
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;     //SuppressUseValidationProblemDetailsForInvalidModelStateResponses;
                //自定义 BadRequest 响应
                options.InvalidModelStateResponseFactory = context =>
                {
                    var problemDetails = new ValidationProblemDetails(context.ModelState);

                    var resultDto = new UnifyResponseDto(ErrorCode.ParameterError, problemDetails.Errors,
                                                         context.HttpContext);

                    return(new BadRequestObjectResult(resultDto)
                    {
                        ContentTypes = { "application/json" }
                    });
                };
            });

            #endregion

            services.AddDIServices();

            #region Swagger

            //Swagger重写PascalCase,改成SnakeCase模式
            services.TryAddEnumerable(ServiceDescriptor.Transient <IApiDescriptionProvider, ApiDescriptionProvider>());

            //Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo()
                {
                    Title = "LinCms", Version = "v1"
                });
                var security = new OpenApiSecurityRequirement()
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference()
                            {
                                Id   = "Bearer",
                                Type = ReferenceType.SecurityScheme
                            }
                        },
                        Array.Empty <string>()
                    }
                };
                options.AddSecurityRequirement(security); //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",          //jwt默认的参数名称
                    In          = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = SecuritySchemeType.ApiKey
                });

                string xmlPath = Path.Combine(AppContext.BaseDirectory,
                                              $"{typeof(Startup).Assembly.GetName().Name}.xml");
                options.IncludeXmlComments(xmlPath);
            });

            #endregion


            //应用程序级别设置

            services.Configure <FormOptions>(options =>
            {
                //单个文件上传的大小限制为8 MB      默认134217728 应该是128MB
                options.MultipartBodyLengthLimit = 1024 * 1024 * 8;     //8MB
            });

            #region 分布式事务一致性CAP

            IConfigurationSection configurationSection = Configuration.GetSection("ConnectionStrings:MySql");
            services.AddCap(x =>
            {
                x.UseMySql(configurationSection.Value);

                x.UseRabbitMQ(options =>
                {
                    options.HostName    = Configuration["RabbitMQ:HostName"];
                    options.UserName    = Configuration["RabbitMQ:UserName"];
                    options.Password    = Configuration["RabbitMQ:Password"];
                    options.VirtualHost = Configuration["RabbitMQ:VirtualHost"];
                });

                x.UseDashboard();
                x.FailedRetryCount        = 5;
                x.FailedThresholdCallback = (type) =>
                {
                    Console.WriteLine(
                        $@"A message of type {type} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {type.Message.GetName()}");
                };
            });

            #endregion

            ////之前请注入AddCsRedisCore,内部实现IDistributedCache接口
            //services.AddIpRateLimiting(Configuration);

            //services.AddHealthChecks();
        }
 private static bool Contains(this IEnumerable<ServiceDescriptor> serviceDescriptors, ServiceDescriptor serviceDescriptor)
 {
     return serviceDescriptors.Any(x => x.ImplementationType == serviceDescriptor.ImplementationType);
 }
        public void Resolve(IServiceCollection serviceCollection)
        {
            if (serviceCollection == null)
            {
                throw new ArgumentNullException(nameof(serviceCollection));
            }
            // serviceCollection.Options.AllowOverridingRegistrations = true;
            var priorityCache = new Dictionary <string, int>();


            LoadReferencingAssemblies();

            var type = typeof(IDependencyMapping);
            var dependencyRegisterList = AppDomain.CurrentDomain
                                         .GetAssemblies().Where(asm => _registerdCompanyNames.Any(asm.FullName.StartsWith))
                                         .SelectMany(s => s.GetTypes())
                                         .Where(p => type.IsAssignableFrom(p) && p.IsClass && !p.IsAbstract);

            foreach (var dependencyRegister in dependencyRegisterList)
            {
                var dependencyMapping = (IDependencyMapping)Activator.CreateInstance(dependencyRegister);
                var typesToRegister   = dependencyMapping.GetTypesToRegister();

                foreach (var typeToRegister in typesToRegister)
                {
                    if (!string.IsNullOrEmpty(typeToRegister.TypeFrom.FullName))
                    {
                        var existingPriority = priorityCache.ContainsKey(typeToRegister.TypeFrom.FullName) ? priorityCache[typeToRegister.TypeFrom.FullName] : 0;
                        if (typeToRegister.Priority > 0)
                        {
                            if (typeToRegister.Priority > existingPriority)
                            {
                                var descriptor = new ServiceDescriptor(typeToRegister.TypeFrom, typeToRegister.TypeTo, GetLifeStyle(typeToRegister.Lifestyle));
                                serviceCollection.Add(descriptor);
                            }

                            if (priorityCache.ContainsKey(typeToRegister.TypeFrom.FullName))
                            {
                                if (priorityCache[typeToRegister.TypeFrom.FullName] < typeToRegister.Priority)
                                {
                                    priorityCache[typeToRegister.TypeFrom.FullName] = typeToRegister.Priority;
                                }
                            }
                            else
                            {
                                priorityCache.Add(typeToRegister.TypeFrom.FullName, typeToRegister.Priority);
                            }
                        }
                        else
                        {
                            if (existingPriority <= typeToRegister.Priority)
                            {
                                var descriptor = new ServiceDescriptor(typeToRegister.TypeFrom, typeToRegister.TypeTo, GetLifeStyle(typeToRegister.Lifestyle));
                                serviceCollection.Add(descriptor);
                            }
                        }
                    }
                }
            }

            ServiceLifetime GetLifeStyle(ObjectLifeStyle?code)
            {
                switch (code)
                {
                case ObjectLifeStyle.Scoped:
                    return(ServiceLifetime.Scoped);

                case ObjectLifeStyle.Singleton:
                    return(ServiceLifetime.Singleton);

                case ObjectLifeStyle.Transient:
                    return(ServiceLifetime.Transient);

                default:
                    return(ServiceLifetime.Transient);
                }
            }
        }