-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHostingModule.cs
69 lines (62 loc) · 2.16 KB
/
HostingModule.cs
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
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Nerosoft.Euonia.Modularity;
namespace Nerosoft.Euonia.Hosting;
/// <summary>
/// The HostingModule class contains methods used to configure the hosting environment.
/// </summary>
public class HostingModule : ModuleContextBase
{
/// <inheritdoc />
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.TryAddScoped<RequestContextAccessor>(_ => GetRequestContext);
context.Services.AddSerilog();
context.Services.AddScopeTransformation();
context.Services.AddUserPrincipal();
context.Services.AddObjectAccessor<IApplicationBuilder>();
context.Services.AddTransient<ExceptionHandlingMiddleware>();
static RequestContext GetRequestContext(IServiceProvider provider)
{
var context = provider.GetService<IHttpContextAccessor>()?.HttpContext;
if (context == null)
{
return null;
}
return new RequestContext
{
RequestHeaders = context.Request
.Headers
.ToDictionary(t => t.Key, t => t.Value.ToString()),
ConnectionId = context.Connection.Id,
User = context.User,
RemotePort = context.Connection.RemotePort,
RemoteIpAddress = context.Connection.RemoteIpAddress,
RequestAborted = context.RequestAborted,
IsWebSocketRequest = context.WebSockets.IsWebSocketRequest,
TraceIdentifier = context.TraceIdentifier,
RequestServices = context.RequestServices
};
}
}
/// <inheritdoc />
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
base.OnApplicationInitialization(context);
var app = context.GetApplicationBuilder();
app.UseMiddleware<RequestTraceMiddleware>();
app.UseMiddleware<ExceptionHandlingMiddleware>();
// Setup the ServiceProvider for IServiceAccessor.
app.Use((httpContext, next) =>
{
var accessor = httpContext.RequestServices.GetService<IServiceAccessor>();
if (accessor != null)
{
accessor.ServiceProvider = httpContext.RequestServices;
}
return next();
});
}
}