181 lines
7.1 KiB
C#
Raw Normal View History

2017-04-17 12:28:12 +02:00
using Basket.API.Infrastructure.Filters;
using Basket.API.IntegrationEvents.EventHandling;
using Basket.API.IntegrationEvents.Events;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
2017-04-17 12:28:12 +02:00
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ;
using Microsoft.eShopOnContainers.Services.Basket.API.Auth.Server;
using Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.EventHandling;
using Microsoft.eShopOnContainers.Services.Basket.API.IntegrationEvents.Events;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
2017-04-17 12:28:12 +02:00
using Microsoft.Extensions.HealthChecks;
using Microsoft.Extensions.Logging;
2016-10-17 20:10:18 -07:00
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
2017-04-17 12:28:12 +02:00
using StackExchange.Redis;
using System.Linq;
2016-10-17 20:10:18 -07:00
using System.Net;
2017-03-23 19:10:55 +01:00
using System.Threading.Tasks;
using System;
2017-05-08 13:36:31 +02:00
using Microsoft.eShopOnContainers.Services.Basket.API.Services;
using Microsoft.AspNetCore.Http;
using Autofac;
using Autofac.Extensions.DependencyInjection;
namespace Microsoft.eShopOnContainers.Services.Basket.API
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
2017-03-23 19:10:55 +01:00
services.AddHealthChecks(checks =>
{
2017-03-31 12:47:56 +02:00
checks.AddValueTaskCheck("HTTP Endpoint", () => new ValueTask<IHealthCheckResult>(HealthCheckResult.Healthy("Ok")));
2017-03-23 19:10:55 +01:00
});
// Add framework services.
services.AddMvc(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
}).AddControllersAsServices();
2016-10-17 20:10:18 -07:00
services.Configure<BasketSettings>(Configuration);
2017-02-26 13:03:46 -05:00
//By connecting here we are making sure that our service
2016-10-17 20:10:18 -07:00
//cannot start until redis is ready. This might slow down startup,
2017-02-26 13:03:46 -05:00
//but given that there is a delay on resolving the ip address
2016-10-17 20:10:18 -07:00
//and then creating the connection it seems reasonable to move
//that cost to startup instead of having the first request pay the
//penalty.
services.AddSingleton<ConnectionMultiplexer>(sp =>
{
2017-04-17 12:28:12 +02:00
var settings = sp.GetRequiredService<IOptions<BasketSettings>>().Value;
var ips = Dns.GetHostAddressesAsync(settings.ConnectionString).Result;
2016-10-17 20:10:18 -07:00
return ConnectionMultiplexer.Connect(ips.First().ToString());
});
2017-04-29 21:58:11 -07:00
services.AddSingleton<IRabbitMQPersistentConnection>(sp =>
2017-04-17 12:28:12 +02:00
{
var settings = sp.GetRequiredService<IOptions<BasketSettings>>().Value;
2017-04-29 21:58:11 -07:00
var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>();
var factory = new ConnectionFactory()
{
HostName = settings.EventBusConnection
};
2017-04-17 12:28:12 +02:00
2017-04-29 21:58:11 -07:00
return new DefaultRabbitMQPersistentConnection(factory, logger);
2017-04-17 12:28:12 +02:00
});
services.AddSwaggerGen();
services.ConfigureSwaggerGen(options =>
{
options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
options.DescribeAllEnumsAsStrings();
options.SingleApiVersion(new Swashbuckle.Swagger.Model.Info()
{
Title = "Basket HTTP API",
Version = "v1",
Description = "The Basket Service HTTP API",
TermsOfService = "Terms Of Service"
});
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
2017-05-08 13:36:31 +02:00
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
2016-10-17 20:10:18 -07:00
services.AddTransient<IBasketRepository, RedisBasketRepository>();
2017-05-08 13:36:31 +02:00
services.AddTransient<IIdentityService, IdentityService>();
RegisterServiceBus(services);
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
}
private void RegisterServiceBus(IServiceCollection services)
{
services.AddSingleton<IEventBus, EventBusRabbitMQ>();
services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();
services.AddTransient<ProductPriceChangedIntegrationEventHandler>();
services.AddTransient<OrderStartedIntegrationEventHandler>();
}
// 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(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseStaticFiles();
// Use frameworks
app.UseCors("CorsPolicy");
ConfigureAuth(app);
2016-11-24 15:31:33 +01:00
app.UseMvcWithDefaultRoute();
app.UseSwagger()
.UseSwaggerUi();
2017-04-17 12:28:12 +02:00
ConfigureEventBus(app);
}
protected virtual void ConfigureAuth(IApplicationBuilder app)
{
var identityUrl = Configuration.GetValue<string>("IdentityUrl");
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = identityUrl.ToString(),
ScopeName = "basket",
RequireHttpsMetadata = false
});
2017-04-17 12:28:12 +02:00
}
protected virtual void ConfigureEventBus(IApplicationBuilder app)
{
var catalogPriceHandler = app.ApplicationServices
.GetService<IIntegrationEventHandler<ProductPriceChangedIntegrationEvent>>();
var orderStartedHandler = app.ApplicationServices
.GetService<IIntegrationEventHandler<OrderStartedIntegrationEvent>>();
var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>();
eventBus.Subscribe<OrderStartedIntegrationEvent, OrderStartedIntegrationEventHandler>();
2017-04-17 12:28:12 +02:00
}
}
}