Browse Source

Merged conent from Startup.cs to Program.cs

pull/1755/head
Sumit Ghosh 3 years ago
parent
commit
2766ea86df
5 changed files with 372 additions and 15 deletions
  1. +4
    -0
      src/Services/Basket/Basket.API/Basket.API.csproj
  2. +353
    -13
      src/Services/Basket/Basket.API/Program.cs
  3. +1
    -1
      src/Services/Basket/Basket.API/Properties/launchSettings.json
  4. +6
    -1
      src/Services/Basket/Basket.API/appsettings.json
  5. +8
    -0
      src/Tests/Services/Application.FunctionalTests/Properties/launchSettings.json

+ 4
- 0
src/Services/Basket/Basket.API/Basket.API.csproj View File

@ -9,6 +9,10 @@
<LangVersion>preview</LangVersion>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Startup.cs" />
</ItemGroup>
<ItemGroup>
<Content Update="web.config">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>


+ 353
- 13
src/Services/Basket/Basket.API/Program.cs View File

@ -1,14 +1,22 @@
var configuration = GetConfiguration();
Log.Logger = CreateSerilogLogger(configuration);
try
{
Log.Information("Configuring web host ({ApplicationContext})...", Program.AppName);
var host = BuildWebHost(configuration, args);
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddConfiguration(configuration);
ConfigureServices(builder);
BuildWebHost(builder);
var app = builder.Build();
ConfigureRequestPipeline(app);
Log.Information("Starting web host ({ApplicationContext})...", Program.AppName);
host.Run();
app.Run();
return 0;
}
@ -22,9 +30,78 @@ finally
Log.CloseAndFlush();
}
IWebHost BuildWebHost(IConfiguration configuration, string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(false)
/// <summary>
/// / Method to help configure services
/// </summary>
void ConfigureServices(WebApplicationBuilder builder)
{
builder.Services.AddGrpc(options =>
{
options.EnableDetailedErrors = true;
});
builder.Services.AddApplicationInsightsTelemetry(configuration);
builder.Services.AddApplicationInsightsKubernetesEnricher();
builder.Services.AddControllers(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
options.Filters.Add(typeof(ValidateModelStateFilter));
}).AddApplicationPart(typeof(BasketController).Assembly)
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
RegisterOpenAPIConfig(builder);
RegisterAuthService(builder);
RegisterHeathCheckConfigs(builder);
RegisterRedisDataStore(builder);
RegisterEventBusConnection(builder);
RegisterEventBus(builder);
builder.Services.Configure<BasketSettings>(configuration);
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.SetIsOriginAllowed((host) => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddTransient<IBasketRepository, RedisBasketRepository>();
builder.Services.AddTransient<IIdentityService, IdentityService>();
builder.Services.AddOptions();
builder.Services.AddAutofac(container =>
{
container.Populate(builder.Services);
});
}
/// <summary>
/// Method to configure app request pipeline.
///
/// </summary>
void ConfigureRequestPipeline(WebApplication app)
{
UsePathBase(app);
UseOpenAPI(app);
app.UseRouting();
app.UseCors("CorsPolicy");
UseConfiguredAuth(app);
app.UseStaticFiles();
UseMappedEndpoints(app);
UseEventBus(app);
}
void BuildWebHost(WebApplicationBuilder builder)
{
builder.WebHost.CaptureStartupErrors(false)
.ConfigureKestrel(options =>
{
var ports = GetDefinedPorts(configuration);
@ -45,10 +122,274 @@ IWebHost BuildWebHost(IConfiguration configuration, string[] args) =>
options.ConfigPath = "/Failing";
options.NotFilteredPaths.AddRange(new[] { "/hc", "/liveness" });
})
.UseStartup<Startup>()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseSerilog()
.Build();
.UseSerilog();
}
void UseEventBus(IApplicationBuilder app)
{
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>();
eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>();
}
void UseMappedEndpoints(IApplicationBuilder app)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<BasketService>();
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
//endpoints.MapGet("/_proto/", async ctx =>
//{
// ctx.Response.ContentType = "text/plain";
// using var fs = new FileStream(Path.Combine(env.ContentRootPath, "Proto", "basket.proto"), FileMode.Open, FileAccess.Read);
// using var sr = new StreamReader(fs);
// while (!sr.EndOfStream)
// {
// var line = await sr.ReadLineAsync();
// if (line != "/* >>" || line != "<< */")
// {
// await ctx.Response.WriteAsync(line);
// }
// }
//});
endpoints.MapHealthChecks("/hc", new HealthCheckOptions()
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
endpoints.MapHealthChecks("/liveness", new HealthCheckOptions
{
Predicate = r => r.Name.Contains("self")
});
});
}
void UsePathBase(IApplicationBuilder app)
{
var pathBase = configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
app.UsePathBase(pathBase);
}
}
void UseOpenAPI(IApplicationBuilder app)
{
var pathBase = configuration["PATH_BASE"];
app.UseSwagger()
.UseSwaggerUI(setup =>
{
setup.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Basket.API V1");
setup.OAuthClientId("basketswaggerui");
setup.OAuthAppName("Basket Swagger UI");
});
}
void UseConfiguredAuth(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseAuthorization();
}
void RegisterOpenAPIConfig(WebApplicationBuilder builder)
{
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "eShopOnContainers - Basket HTTP API",
Version = "v1",
Description = "The Basket Service HTTP API"
});
options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
AuthorizationUrl = new Uri($"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize"),
TokenUrl = new Uri($"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/token"),
Scopes = new Dictionary<string, string>()
{
{ "basket", "Basket API" }
}
}
}
});
options.OperationFilter<AuthorizeCheckOperationFilter>();
});
}
void RegisterAuthService(WebApplicationBuilder builder)
{
// prevent from mapping "sub" claim to nameidentifier.
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");
var identityUrl = configuration.GetValue<string>("IdentityUrl");
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = identityUrl;
options.RequireHttpsMetadata = false;
options.Audience = "basket";
});
}
void RegisterHeathCheckConfigs(WebApplicationBuilder builder)
{
var hcBuilder = builder.Services.AddHealthChecks();
hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());
hcBuilder
.AddRedis(
configuration["ConnectionString"],
name: "redis-check",
tags: new string[] { "redis" });
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
hcBuilder
.AddAzureServiceBusTopic(
configuration["EventBusConnection"],
topicName: "eshop_event_bus",
name: "basket-servicebus-check",
tags: new string[] { "servicebus" });
}
else
{
hcBuilder
.AddRabbitMQ(
$"amqp://{configuration["EventBusConnection"]}",
name: "basket-rabbitmqbus-check",
tags: new string[] { "rabbitmqbus" });
}
}
void RegisterRedisDataStore(WebApplicationBuilder builder)
{
//By connecting here we are making sure that our service
//cannot start until redis is ready. This might slow down startup,
//but given that there is a delay on resolving the ip address
//and then creating the connection it seems reasonable to move
//that cost to startup instead of having the first request pay the
//penalty.
builder.Services.AddSingleton<ConnectionMultiplexer>(sp =>
{
var settings = sp.GetRequiredService<IOptions<BasketSettings>>().Value;
var configuration = ConfigurationOptions.Parse(settings.ConnectionString, true);
configuration.ResolveDns = true;
return ConnectionMultiplexer.Connect(configuration);
});
}
void RegisterEventBusConnection(WebApplicationBuilder builder)
{
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
builder.Services.AddSingleton<IServiceBusPersisterConnection>(sp =>
{
var serviceBusConnectionString = configuration["EventBusConnection"];
var serviceBusConnection = new ServiceBusConnectionStringBuilder(serviceBusConnectionString);
var subscriptionClientName = configuration["SubscriptionClientName"];
return new DefaultServiceBusPersisterConnection(serviceBusConnection, subscriptionClientName);
});
}
else
{
builder.Services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
{
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = configuration["EventBusConnection"],
DispatchConsumersAsync = true
};
if (!string.IsNullOrEmpty(configuration["EventBusUserName"]))
{
factory.UserName = configuration["EventBusUserName"];
}
if (!string.IsNullOrEmpty(configuration["EventBusPassword"]))
{
factory.Password = configuration["EventBusPassword"];
}
var retryCount = 5;
if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(configuration["EventBusRetryCount"]);
}
return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount);
});
}
}
void RegisterEventBus(WebApplicationBuilder builder)
{
if (configuration.GetValue<bool>("AzureServiceBusEnabled"))
{
builder.Services.AddSingleton<IEventBus, EventBusServiceBus>(sp =>
{
var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>();
var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
return new EventBusServiceBus(serviceBusPersisterConnection, logger,
eventBusSubcriptionsManager, iLifetimeScope);
});
}
else
{
builder.Services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp =>
{
var subscriptionClientName = configuration["SubscriptionClientName"];
var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>();
//var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>();
var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>();
var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>();
var retryCount = 5;
if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"]))
{
retryCount = int.Parse(configuration["EventBusRetryCount"]);
}
//return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
// TO DO
return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, null, eventBusSubcriptionsManager, subscriptionClientName, retryCount);
});
}
builder.Services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
builder.Services.AddTransient<ProductPriceChangedIntegrationEventHandler>();
builder.Services.AddTransient<OrderStartedIntegrationEventHandler>();
}
Serilog.ILogger CreateSerilogLogger(IConfiguration configuration)
{
@ -94,8 +435,7 @@ IConfiguration GetConfiguration()
}
public class Program
{
public static string Namespace = typeof(Startup).Namespace;
public static string AppName = Namespace.Substring(Namespace.LastIndexOf('.', Namespace.LastIndexOf('.') - 1) + 1);
{
public static string Namespace = typeof(Program).Namespace;
public static string AppName = "Basket.API";
}

+ 1
- 1
src/Services/Basket/Basket.API/Properties/launchSettings.json View File

@ -19,7 +19,7 @@
"Microsoft.eShopOnContainers.Services.Basket.API": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "http://localhost:55103/",
"launchUrl": "http://localhost:5103/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}


+ 6
- 1
src/Services/Basket/Basket.API/appsettings.json View File

@ -26,5 +26,10 @@
"Name": "eshop",
"ClientId": "your-clien-id",
"ClientSecret": "your-client-secret"
}
},
"IdentityUrlExternal": "http://localhost:5105",
"IdentityUrl": "http://localhost:5105",
"ConnectionString": "127.0.0.1",
"AzureServiceBusEnabled": false,
"EventBusConnection": "localhost"
}

+ 8
- 0
src/Tests/Services/Application.FunctionalTests/Properties/launchSettings.json View File

@ -0,0 +1,8 @@
{
"profiles": {
"WSL": {
"commandName": "WSL2",
"distributionName": ""
}
}
}

Loading…
Cancel
Save