Exemplo n.º 1
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
                              IApplicationLifetime applicationLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(options =>
            {
                options.AllowAnyHeader();
                options.AllowAnyMethod();
                options.AllowAnyOrigin();
            });

            loggerFactory.AddConsole(ConfigurationRoot.GetSection("Logging"));
            loggerFactory.AddDebug();

            //Swagger
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Product Catalog Api V1"); });

            app.UseHealthChecks("/health");                                //Health check
            app.UseHealthChecksUI(config => config.UIPath = "/health-ui"); //Health check user interface

            app.UseMvc();

            //start micro services
            Services = app.ApplicationServices;
            applicationLifetime.ApplicationStarted.Register(OnStart);
            applicationLifetime.ApplicationStopping.Register(OnStopping);
            applicationLifetime.ApplicationStopped.Register(OnStopped);
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder
            .RegisterType <DefaultTimeService>()
            .As <ITimeService>()
            .WithParameter("settings", ConfigurationRoot.GetSection("Time").Get <DefaultTimeServiceSettings>())
            .InstancePerLifetimeScope();

            builder
            .RegisterAssemblyTypes(typeof(RegistrationService).Assembly)
            .AssignableTo <IDomainService>()
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <RegistrationsViewModelService>()
            .As <IRegistrationsViewModelService>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <RazorHtmlLayoutGenerator>()
            .As <IRazorHtmlLayoutGenerator>()
            .InstancePerLifetimeScope();

            builder
            .RegisterType <MailNotificationService>()
            .As <IMailNotificationService>()
            .InstancePerLifetimeScope();
        }
Exemplo n.º 3
0
        protected AbstractExtensionBuilderDependency(string name, IExtensionBuilderDependency parentDependency = null)
            : base(name)
        {
            if (parentDependency.IsNotNull())
            {
                BaseDirectory     = parentDependency.BaseDirectory;
                ConfigDirectory   = parentDependency.ConfigDirectory;
                ReportDirectory   = parentDependency.ReportDirectory;
                ResourceDirectory = parentDependency.ResourceDirectory;

                ConfigurationRoot = parentDependency.ConfigurationRoot;

                if (ConfigurationRoot.IsNotNull())
                {
                    Configuration = ConfigurationRoot.GetSection(Name);
                }

                ParentDependency = parentDependency;
            }
            else
            {
                var currentDirectory = Environment.CurrentDirectory.WithoutDevelopmentRelativePath();

                BaseDirectory     = currentDirectory;
                ConfigDirectory   = currentDirectory.CombinePath(CoreSettings.Preference.ConfigsFolder);
                ReportDirectory   = currentDirectory.CombinePath(CoreSettings.Preference.ReportsFolder);
                ResourceDirectory = currentDirectory.CombinePath(CoreSettings.Preference.ResourcesFolder);
            }
        }
Exemplo n.º 4
0
 public IEnumerable <string> GetExcludeFiles(string intepubDirectoryPath)
 {
     return(ConfigurationRoot
            .GetSection("CheckVersionProcess.ExcludeDirectories")
            .GetChildren()
            .Select(x => Path.Combine(intepubDirectoryPath, x.Value))
            .ToList());
 }
Exemplo n.º 5
0
 protected override void Load(ContainerBuilder builder)
 {
     builder
     .RegisterType <MailKitBasedMailService>()
     .As <IMailService>()
     .WithParameter("settings", ConfigurationRoot.GetSection("Mail:Smtp").Get <MailKitBasedMailServiceSettings>())
     .SingleInstance();
 }
Exemplo n.º 6
0
 private void Excel(ContainerBuilder builder)
 {
     builder
     .RegisterType <ExcelGenerator>()
     .As <IExcelGenerator>()
     .WithParameter("settings", ConfigurationRoot.GetSection("Documents:Excel").Get <ExcelSettings>())
     .SingleInstance();
 }
Exemplo n.º 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public override IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(typeof(IPromotionClient).Assembly.GetName());

            services.AddHttpClient("HttpTimeoutForCommitWorkOrder", client => {
                client.Timeout = TimeSpan.Parse(ConfigurationRoot.GetSection("AppSettings:HttpTimeoutForCommitWorkOrder").Value);//00:00:20
            });

            return(base.ConfigureServices(services));
        }
        protected override void Load(ContainerBuilder builder)
        {
            builder
            .RegisterGeneric(typeof(EntityFrameworkCoreRepository <>))
            .As(typeof(IRepository <>))
            .InstancePerLifetimeScope();

            builder
            .RegisterType <DefaultContext>()
            .As <DbContext>()
            .WithParameter("settings", ConfigurationRoot.GetSection("Persistence").Get <EntityFrameworkSettings>())
            .SingleInstance();
        }
        public void Can_get_config_from_options()
        {
            var services = new ServiceCollection();

            // IOption configuration injection
            services.AddOptions();

            var caraibesConfigs      = new CaraibesConfigs();
            var configurationSection = ConfigurationRoot.GetSection("Weblog");

            services.Configure <CaraibesConfigs>(caConfigs => { configurationSection.Bind(caraibesConfigs); });

            // TODO: then what? What is the benefit of using ServiceCollection
        }
Exemplo n.º 10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(ConfigurationRoot.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddProvider(NullLoggerProvider.Instance);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                //app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            //app.UseIdentity();

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

            app.UserAppConfigRequestServicesMiddleware();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "area",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");


                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "TmAPI V1");
            });
        }
Exemplo n.º 11
0
        private void Pdf(ContainerBuilder builder)
        {
            builder
            .RegisterType <RazorHtmlLayoutGenerator>()
            .As <IRazorHtmlLayoutGenerator>()
            .SingleInstance();

            builder
            .RegisterInstance(new SynchronizedConverter(new PdfTools()))
            .As <IConverter>()
            .SingleInstance();

            builder
            .RegisterType <DinkPdfGenerator>()
            .As <IPdfGenerator>()
            .WithParameter("settings", ConfigurationRoot.GetSection("Documents:Pdf").Get <DinkSettings>())
            .SingleInstance();
        }
Exemplo n.º 12
0
        private void ConfigureLogging(IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(ConfigurationRoot.GetSection("Logging"));

            if (env.IsDevelopment())
            {
                loggerFactory.AddDebug();
            }
            else
            {
                loggerFactory.AddAzureWebAppDiagnostics(
                    new AzureAppServicesDiagnosticsSettings
                {
                    OutputTemplate =
                        "{Timestamp:yyyy-MM-dd HH:mm:ss zzz} [{Level}] {RequestId}-{SourceContext}: {Message}{NewLine}{Exception}"
                });
            }
        }
Exemplo n.º 13
0
        Create_Should_Return_Previous_Object_If_Configuration_Had_Been_Changed_And_Is_Invalid_To_Create_New_One()
        {
            var tesTConfigClassProvider = new TesTConfigClassProvider();

            tesTConfigClassProvider.Set(ExtensionMethods.CreateKeyName <SampleConfiguration>(x => x.IntValue), "10");
            var configuration = new ConfigurationRoot(new List <IConfigurationProvider> {
                tesTConfigClassProvider
            });
            var factory = new TrackingConfigurationChangesFactory <SampleConfiguration>(
                configuration.GetSection(nameof(SampleConfiguration)),
                BindPolicy.Default);
            var lastValidConfig = factory.Create();

            tesTConfigClassProvider.Clear();
            // act && assert
            var actualConfig = factory.Create();

            Assert.Same(lastValidConfig, actualConfig);
        }
Exemplo n.º 14
0
        public static IContainer CompositionRoot()
        {
            LoadAppSettings();

            var builder = new ContainerBuilder();

            builder.RegisterType <Application>();

            /*
             * var dumpToFilePath = ConfigurationRoot.GetSection("ExtractionDetails")["ExtractionFilePath"];
             * builder.RegisterType<JsonRepository>()
             *  .As<IRepository>()
             *  .WithParameter(new NamedParameter("filePath", dumpToFilePath));*/
            var connectionString = ConfigurationRoot.GetConnectionString("astroEventsDb");

            builder.RegisterType <SqliteRepository>()
            .As <IRepository>()
            .WithParameter(new NamedParameter("connectionString", connectionString));

            var astroWikiUrl = ConfigurationRoot.GetSection("ExtractionDetails")["AstroWikiAPIUrl"];

            builder.RegisterType <ScrappyService>()
            .As <IScrapingService>()
            .WithParameter(new NamedParameter("astroWikiUrl", astroWikiUrl));

            var loggerFactory = LoggerFactory.Create(b =>
            {
                b.AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
                .AddFilter("WikiScraper.Program", LogLevel.Debug)
                .AddConsole();
            });
            var logger = loggerFactory.CreateLogger <Program>();

            builder.RegisterInstance(logger).As <ILogger>();

            builder.RegisterType <AstroParser>().As <IParser>();

            return(builder.Build());
        }
Exemplo n.º 15
0
 public IConfigurationSection GetSection(string key) => _configuration.GetSection(key);
Exemplo n.º 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("Cors", builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }));
            services.AddSingleton(ConfigurationRoot);

            //Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Product Catalog API", Version = "v1"
                });
            });

            services.Configure <ServiceBusSettings>(options => ConfigurationRoot.GetSection("ServiceBus").Bind(options));
            services.Configure <ServiceBusQueuesSettings>(options => ConfigurationRoot.GetSection("ServiceBusQueues").Bind(options));
            services.Configure <ConnectionStringSettings>(options => ConfigurationRoot.GetSection("ConnectionStrings").Bind(options));

            var serviceBusSettings = new ServiceBusSettings();

            ConfigurationRoot.GetSection("ServiceBus").Bind(serviceBusSettings);
            services.AddSingleton(provider => BusConfigurator.ConfigureBus(serviceBusSettings));
            services.AddSingleton <IBus>(provider => provider.GetService <IBusControl>());

            //var db = new DbContextOptionsBuilder<ProductDbContext>()
            //    .UseInMemoryDatabase(databaseName: "Product").Options;

            //using (var context = new ProductDbContext(db))
            //{
            //    var product = new Product
            //    {
            //        Code = "asd",
            //        Name = "aaaa",
            //        Photo = "asdasd",
            //        Price = 23.4m
            //    };

            //    context.Products.Add(product);
            //    context.SaveChanges();
            //}

            //services.AddDbContext<ProductDbContext>(options => options.UseSqlServer(ConfigurationRoot.GetConnectionString("DatabaseConnection")));
            //services.AddDbContext<ProductDbContext>(options =>
            //    options.UseInMemoryDatabase(ConfigurationRoot.GetConnectionString("DefaultConnection")));

            services.AddMemoryCache();
            services.AddOptions();
            services.AddMvc();
            services.AddHealthChecks();   //Health check
            services.AddHealthChecksUI(); //Health check User interface

            //Api Versioning
            services.AddApiVersioning(version =>
            {
                version.AssumeDefaultVersionWhenUnspecified = true;
                version.DefaultApiVersion = new ApiVersion(1, 0);
                version.ReportApiVersions = true;
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
        }
Exemplo n.º 17
0
 public JiraClient(ILoggerFactory loggerFactory, IHttpClientFactory clientFactory, ConfigurationRoot configuraton)
 {
     _logger        = loggerFactory.CreateLogger <KaitenClient>();
     _clientFactory = clientFactory;
     _configuration = configuraton.GetSection("jira").Get <JiraConfiguration>();
 }
Exemplo n.º 18
0
        private void Init()
        {
            //problems:
            //a: if multiple providers provide values for a collection, the values get added
            //doubleMerge: when having Config inside Config, Bind will be executed twice
            //   Bind binds recursive, so the subConfig Constructor calls Init (bind#1) and then binds again below (bind#2)
            //c: On the init call from Change token, existing element will be bound again
            //d: setting classes will be registered as singletons, but when using sub settings is used,
            //   you will end up with separate instances despite registrations. To handle this correctly,
            //   sub settings would need to be resolved from ioc, and set in this instance.


            #region doubleMerge

            //create sub Settings by us here, so they will not get double bound here
            //after binding below, the constructor of the sub class will bind, and then the binding here will bind it again
            //so with merge behaviour of binding, values of array will be doubled
            //https://github.com/dotnet/runtime/issues/46988

            //idea for doubleMerge workaround:
            // construct sub configs before binding (has correct values) and replace here after binding.

            var subSettings = new Dictionary <PropertyInfo, object>();
            foreach (var propertyInfo in GetType().GetProperties()
                     .Where(x => x.CanRead && x.CanWrite)
                     .Where(x => typeof(SettingsBase).IsAssignableFrom(x.PropertyType)))
            {
                var subSetting = Activator.CreateInstance(propertyInfo.PropertyType);
                subSettings.Add(propertyInfo, subSetting);
            }

            #endregion


            var sectionPath = GetType().GetSectionPath();
            //read current values from IConfiguration
            if (string.IsNullOrWhiteSpace(sectionPath))
            {
                ConfigurationRoot.Bind(this);
            }
            else
            {
                ConfigurationRoot.GetSection(sectionPath).Bind(this);
            }

            //ApplyReadTransformations
            foreach (var transformation in ConfigurationOptions.StringTransformations)
            {
                StringTransformerBase.TransformObject(this, ConfigurationRoot, transformation.PerformReadTransformation);
            }

            #region doubleMerge

            //set back sub settings
            foreach (var pair in subSettings)
            {
                pair.Key.SetValue(this, pair.Value);
            }

            #endregion
        }
Exemplo n.º 19
0
 /// <summary>
 /// 绑定配置根包含的默认租户配置节(支持加密连接字符串)。
 /// </summary>
 /// <examples>
 /// JSON 配置节点结构参考:
 /// <code>
 /// {
 ///     "DefaultTenant": {
 ///         "Name": "name",
 ///         "Host": "host",
 ///         "DefaultConnectionString": "default connection string",
 ///         "WritingConnectionString": "writing connection string",
 ///         "WritingSeparation": true // or false
 ///     }
 /// }
 /// </code>
 /// </examples>
 /// <exception cref="ArgumentNullException">
 /// this.ConfigurationRoot is null.
 /// </exception>
 /// <param name="validateFactory">给定用于验证连接字符串的工厂方法(可选)。</param>
 /// <returns>返回 <see cref="DataBuilderDependency"/>。</returns>
 public virtual DataBuilderDependency BindDefaultTenant(Func <string, string> validateFactory = null)
 {
     ConfigurationRoot.NotNull(nameof(ConfigurationRoot));
     return(BindDefaultTenant(ConfigurationRoot.GetSection(DefaultTenantSectionName), validateFactory));
 }