public HomeController(IOptions <ExternalApiConfiguration> options,
                       IOptionsSnapshot <ExternalApiConfiguration> optionsSnapshot,
                       ExternalApiConfiguration configurationObject)
 {
     configuration            = options.Value;
     configurationSnapshot    = optionsSnapshot.Value;
     this.configurationObject = configurationObject;
 }
示例#2
0
        /// <summary>
        /// Configure Services
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            Log.Logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();
            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));

            // TODO: look at different way to register loggers
            //https://stackoverflow.com/questions/49300594/cannot-resolve-iloggert-simple-injector-asp-net-core-2-0

            services.AddDbContext <DatabaseContext>(opt => opt.UseSqlServer(Configuration.GetSection("Document").GetValue <string>("ConnectionString")));

            services.AddResponseCaching();
            services.AddResponseCompression(options => {
                options.Providers.Add <GzipCompressionProvider>();
            });

            services.AddMemoryCache();
            services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials().SetPreflightMaxAge(new TimeSpan(0, 15, 0)).Build()));

            JsonConvert.DefaultSettings = (() => {
                var settings = new JsonSerializerSettings();
                settings.Converters.Add(new StringEnumConverter {
                    AllowIntegerValues = false
                });
                return(settings);
            });

            services.AddMvc(options => {
                options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
                options.CacheProfiles.Add("default", new CacheProfile {
                    Duration = 30,
                    Location = ResponseCacheLocation.Any
                });
            })
            .AddJsonOptions(options => {
                options.SerializerSettings.ContractResolver      = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateFormatHandling    = DateFormatHandling.IsoDateFormat;
                options.SerializerSettings.NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore;
                options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter(true));
            });

            services.AddRouting(options => {
                options.LowercaseUrls = true;
            });

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            var authConfig = Configuration.GetSection("IdentityApi");

            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o => {
                o.Authority            = authConfig.GetValue <string>("Authority");
                o.Audience             = authConfig.GetValue <string>("ApiName");
                o.RequireHttpsMetadata = authConfig.GetValue <bool>("RequireHttpsMetadata");
                o.TokenValidationParameters.RoleClaimType = "role";
                o.TokenValidationParameters.NameClaimType = "name";
            });

            //var applicationConfiguration = Configuration.GetSection("ApplicationApi").Get<ApplicationClientConfiguration>();
            //if (string.IsNullOrWhiteSpace(applicationConfiguration.Authentication.Url)) {
            //    applicationConfiguration.Authentication.Url = authConfig.GetValue<string>("Authority") + "/connect/token";
            //}
            //services.AddSingleton<ApplicationClientConfiguration>(applicationConfiguration);

            // Register Hosted Services
            var config    = Configuration.GetSection("ServiceBus");
            var rsettings = new ServiceBusReceiverSettings {
                Address    = config.GetValue <string>("Queue"),
                AppName    = config.GetValue <string>("AppName"),
                Protocol   = config.GetValue <string>("Protocol"),
                PolicyName = config.GetValue <string>("Policy"),
                Key        = config.GetValue <string>("Key"),
                Namespace  = config.GetValue <string>("Namespace"),
                Durable    = 1
                             //, Credits = 1
            };

            services.AddSingleton(rsettings);

            var psettings = new ServiceBusPublisherSettings {
                Address    = config.GetValue <string>("Exchange"),
                AppName    = config.GetValue <string>("AppName"),
                Protocol   = config.GetValue <string>("Protocol"),
                PolicyName = config.GetValue <string>("Policy"),
                Key        = config.GetValue <string>("Key"),
                Namespace  = config.GetValue <string>("Namespace"),
                Durable    = 1
                             //, Credits = 1
            };

            services.AddSingleton(psettings);

            // register all services, handlers and factories
            Assembly.GetEntryAssembly().GetTypes()
            .Where(x => (x.Name.EndsWith("Service") || x.Name.EndsWith("Handler") || x.Name.EndsWith("Factory") || x.Name.EndsWith("Client")) &&
                   x.GetTypeInfo().IsClass &&
                   !x.GetTypeInfo().IsAbstract &&
                   x.GetInterfaces().Any())
            .ToList().ForEach(x => {
                x.GetInterfaces().ToList()
                .ForEach(i => services.AddSingleton(i, x));
            });

            var ExternalApiSection       = Configuration.GetSection("ExternalApi");
            var ExternalApiConfiguration = new ExternalApiConfiguration()
            {
                Url        = ExternalApiSection.GetValue <string>("Url"),
                OutputPath = ExternalApiSection.GetValue <string>("OutputPath")
            };

            services.AddSingleton(ExternalApiConfiguration);
            services.AddTransient <IExternalApiClient, ExternalApiClient>();

            // register domain services
            typeof(HealthService).GetTypeInfo().Assembly.GetTypes()
            .Where(x => (x.Name.EndsWith("Service")) &&
                   x.GetTypeInfo().IsClass &&
                   !x.GetTypeInfo().IsAbstract &&
                   x.GetInterfaces().Any())
            .ToList().ForEach(x => {
                x.GetInterfaces().ToList()
                .ForEach(i => services.AddSingleton(i, x));
            });

            services.AddTransient <IDocumentService, DocumentService>();
            services.AddTransient <IHealthService, HealthService>();

            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info {
                    Version = "v1", Title = "Documents API"
                });
                c.DescribeAllEnumsAsStrings();

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            services.AddSingleton <IDomainEventPublisher, DomainEventPublisher>();
            services.AddSingleton <IDomainEventHandler <ApplicationStateChangedEvent>, ApplicationStateChangedHandler>();
            services.AddSingleton <IDomainEventReceiver, DomainEventReceiver>();

            services.AddSingleton <ITelemetryInitializer, AppInsightsInitializer>();
            services.AddApplicationInsightsTelemetry();

            services.AddAutoMapper(typeof(Startup).Assembly);
        }
 public ExternalApiService(HttpClient client, ILogger <ExternalApiService> logger, IOptions <ExternalApiConfiguration> config)
 {
     _client = client;
     _logger = logger;
     _config = config.Value;
 }
 public DocumentService(DatabaseContext db, IExternalApiClient ExternalApi, ExternalApiConfiguration config)
 {
     this.db          = db;
     this.config      = config;
     this.ExternalApi = ExternalApi;
 }