-
Notifications
You must be signed in to change notification settings - Fork 63
/
Extensions.cs
154 lines (133 loc) · 6.32 KB
/
Extensions.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
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.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using DShop.Common.Handlers;
using DShop.Common.Jaeger;
using DShop.Common.Messages;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using OpenTracing;
using RawRabbit;
using RawRabbit.Common;
using RawRabbit.Configuration;
using RawRabbit.Enrichers.MessageContext;
using RawRabbit.Instantiation;
using RawRabbit.Pipe;
using RawRabbit.Pipe.Middleware;
namespace DShop.Common.RabbitMq
{
public static class Extensions
{
public static IBusSubscriber UseRabbitMq(this IApplicationBuilder app)
=> new BusSubscriber(app);
public static void AddRabbitMq(this ContainerBuilder builder)
{
builder.Register(context =>
{
var configuration = context.Resolve<IConfiguration>();
var options = configuration.GetOptions<RabbitMqOptions>("rabbitMq");
return options;
}).SingleInstance();
builder.Register(context =>
{
var configuration = context.Resolve<IConfiguration>();
var options = configuration.GetOptions<RawRabbitConfiguration>("rabbitMq");
return options;
}).SingleInstance();
var assembly = Assembly.GetCallingAssembly();
builder.RegisterAssemblyTypes(assembly)
.AsClosedTypesOf(typeof(IEventHandler<>))
.InstancePerDependency();
builder.RegisterAssemblyTypes(assembly)
.AsClosedTypesOf(typeof(ICommandHandler<>))
.InstancePerDependency();
builder.RegisterType<Handler>().As<IHandler>()
.InstancePerDependency();
builder.RegisterType<BusPublisher>().As<IBusPublisher>()
.InstancePerDependency();
builder.RegisterInstance(DShopDefaultTracer.Create()).As<ITracer>().SingleInstance()
.PreserveExistingDefaults();
ConfigureBus(builder);
}
private static void ConfigureBus(ContainerBuilder builder)
{
builder.Register<IInstanceFactory>(context =>
{
var options = context.Resolve<RabbitMqOptions>();
var configuration = context.Resolve<RawRabbitConfiguration>();
var namingConventions = new CustomNamingConventions(options.Namespace);
var tracer = context.Resolve<ITracer>();
return RawRabbitFactory.CreateInstanceFactory(new RawRabbitOptions
{
DependencyInjection = ioc =>
{
ioc.AddSingleton(options);
ioc.AddSingleton(configuration);
ioc.AddSingleton<INamingConventions>(namingConventions);
ioc.AddSingleton(tracer);
},
Plugins = p => p
.UseAttributeRouting()
.UseRetryLater()
.UpdateRetryInfo()
.UseMessageContext<CorrelationContext>()
.UseContextForwarding()
.UseJaeger(tracer)
});
}).SingleInstance();
builder.Register(context => context.Resolve<IInstanceFactory>().Create());
}
private class CustomNamingConventions : NamingConventions
{
public CustomNamingConventions(string defaultNamespace)
{
var assemblyName = Assembly.GetEntryAssembly().GetName().Name;
ExchangeNamingConvention = type => GetNamespace(type, defaultNamespace).ToLowerInvariant();
RoutingKeyConvention = type =>
$"{GetRoutingKeyNamespace(type, defaultNamespace)}{type.Name.Underscore()}".ToLowerInvariant();
QueueNamingConvention = type => GetQueueName(assemblyName, type, defaultNamespace);
ErrorExchangeNamingConvention = () => $"{defaultNamespace}.error";
RetryLaterExchangeConvention = span => $"{defaultNamespace}.retry";
RetryLaterQueueNameConvetion = (exchange, span) =>
$"{defaultNamespace}.retry_for_{exchange.Replace(".", "_")}_in_{span.TotalMilliseconds}_ms".ToLowerInvariant();
}
private static string GetRoutingKeyNamespace(Type type, string defaultNamespace)
{
var @namespace = type.GetCustomAttribute<MessageNamespaceAttribute>()?.Namespace ?? defaultNamespace;
return string.IsNullOrWhiteSpace(@namespace) ? string.Empty : $"{@namespace}.";
}
private static string GetNamespace(Type type, string defaultNamespace)
{
var @namespace = type.GetCustomAttribute<MessageNamespaceAttribute>()?.Namespace ?? defaultNamespace;
return string.IsNullOrWhiteSpace(@namespace) ? type.Name.Underscore() : $"{@namespace}";
}
private static string GetQueueName(string assemblyName, Type type, string defaultNamespace)
{
var @namespace = type.GetCustomAttribute<MessageNamespaceAttribute>()?.Namespace ?? defaultNamespace;
var separatedNamespace = string.IsNullOrWhiteSpace(@namespace) ? string.Empty : $"{@namespace}.";
return $"{assemblyName}/{separatedNamespace}{type.Name.Underscore()}".ToLowerInvariant();
}
}
private class RetryStagedMiddleware : StagedMiddleware
{
public override string StageMarker { get; } = RawRabbit.Pipe.StageMarker.MessageDeserialized;
public override async Task InvokeAsync(IPipeContext context,
CancellationToken token = new CancellationToken())
{
var retry = context.GetRetryInformation();
if (context.GetMessageContext() is CorrelationContext message)
{
message.Retries = retry.NumberOfRetries;
}
await Next.InvokeAsync(context, token);
}
}
private static IClientBuilder UpdateRetryInfo(this IClientBuilder clientBuilder)
{
clientBuilder.Register(c => c.Use<RetryStagedMiddleware>());
return clientBuilder;
}
}
}