-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathStartupExtensions.cs
More file actions
154 lines (135 loc) · 5.82 KB
/
StartupExtensions.cs
File metadata and controls
154 lines (135 loc) · 5.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using AutoMapper;
using HwProj.EventBus.Client;
using HwProj.EventBus.Client.Implementations;
using HwProj.EventBus.Client.Interfaces;
using HwProj.Utils.Authorization;
using HwProj.Utils.Configuration.Middleware;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Polly;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using Swashbuckle.AspNetCore.Swagger;
namespace HwProj.Utils.Configuration
{
public static class StartupExtensions
{
public static IServiceCollection ConfigureHwProjServices(this IServiceCollection services, string serviceName)
{
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())
.AddCors()
.AddMvc()
.AddJsonOptions(options =>
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = serviceName, Version = "v1" });
if (serviceName == "API Gateway")
{
c.AddSecurityDefinition("Bearer",
new ApiKeyScheme
{
In = "header",
Description = "Please enter into field the word 'Bearer' following by space and JWT",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
{ "Bearer", Enumerable.Empty<string>() },
});
}
});
if (serviceName != "AuthService API")
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false; //TODO: dev env setting
x.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = "AuthService",
ValidateIssuer = true,
ValidateAudience = false,
ValidateLifetime = true,
IssuerSigningKey = AuthorizationKey.SecurityKey,
ValidateIssuerSigningKey = true
};
});
}
services.AddTransient<NoApiGatewayMiddleware>();
services.AddHttpContextAccessor();
return services;
}
public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration)
{
var eventBusSection = configuration.GetSection("EventBus");
var retryCount = 5;
if (!string.IsNullOrEmpty(eventBusSection["EventBusRetryCount"]))
{
retryCount = int.Parse(eventBusSection["EventBusRetryCount"]);
}
services.AddSingleton(sp => Policy.Handle<SocketException>()
.Or<BrokerUnreachableException>()
.WaitAndRetry(retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
services.AddSingleton<IConnectionFactory, ConnectionFactory>(sp => new ConnectionFactory
{
HostName = eventBusSection["EventBusHostName"],
UserName = eventBusSection["EventBusUserName"],
Password = eventBusSection["EventBusPassword"],
VirtualHost = eventBusSection["EventBusVirtualHost"]
});
services.AddSingleton<IDefaultConnection, DefaultConnection>();
services.AddSingleton<IEventBus, EventBusRabbitMq>();
var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).ToList();
var eventTypes = types.Where(x => typeof(Event).IsAssignableFrom(x));
foreach (var eventType in eventTypes)
{
var fullTypeInterface = typeof(IEventHandler<>).MakeGenericType(eventType);
var handlersTypes = types.Where(x =>
fullTypeInterface.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract);
foreach (var handlerType in handlersTypes)
{
services.AddTransient(handlerType);
}
}
return services;
}
public static IApplicationBuilder ConfigureHwProj(this IApplicationBuilder app, IHostingEnvironment env,
string serviceName)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage()
.UseSwagger()
.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", serviceName); });
}
else
{
app.UseHsts();
}
app.UseAuthentication();
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
app.UseMvc();
return app;
}
}
}