Skip to content

Commit 14e3ada

Browse files
author
欧俊
committed
fix bug:修改处理类的注册方式,修复处理类找不到注册的bug
1 parent ac65875 commit 14e3ada

6 files changed

Lines changed: 117 additions & 51 deletions

File tree

RabbitMQ.EventBus.AspNetCore.Sample/Startup.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
using Microsoft.Extensions.DependencyInjection;
66
using Microsoft.Extensions.Diagnostics.HealthChecks;
77
using Microsoft.Extensions.Hosting;
8+
using RabbitMQ.EventBus.AspNetCore.Events;
9+
using RabbitMQ.EventBus.AspNetCore.Simple.Controllers;
810
using System;
911
using System.Reflection;
1012

@@ -28,6 +30,7 @@ public void ConfigureServices(IServiceCollection services)
2830
services.AddHealthChecks();
2931

3032

33+
//services.AddTransient<IEventHandler<MessageBody>, MessageBodyHandle>();
3134
services.AddRabbitMQEventBus("localhost", 5672, "guest", "guest", "", eventBusOptionAction: eventBusOption =>
3235
{
3336
eventBusOption.ClientProvidedAssembly(assemblyName);
@@ -59,12 +62,13 @@ public void ConfigureServices(IServiceCollection services)
5962
}
6063

6164
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
62-
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
65+
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IRabbitMQEventBus rabbitMQ)
6366
{
6467
if (env.IsDevelopment())
6568
{
6669
app.UseDeveloperExceptionPage();
6770
}
71+
app.UseRabbitmqEventBus();
6872
app.UseRouting();
6973
app.UseEndpoints(endpoints =>
7074
{

src/RabbitMQ.EventBus.AspNetCore/DefaultRabbitMQEventBusV2.cs

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
namespace RabbitMQ.EventBus.AspNetCore;
1+
using Microsoft.Extensions.Logging;
2+
3+
namespace RabbitMQ.EventBus.AspNetCore;
24

35
internal class DefaultRabbitMQEventBusV2 : IRabbitMQEventBus
46
{
@@ -252,14 +254,13 @@ public void Subscribe(Type eventType, Type responseType, string type = "topic")
252254

253255
private async Task<string> ProcessEventAsync(string body, Type eventType, Type responseType, BasicDeliverEventArgs args)
254256
{
255-
using var scope = _serviceProvider.CreateScope();
256-
Type eventHandlerType = typeof(IEventResponseHandler<,>);
257-
dynamic eventHandler = scope.ServiceProvider.GetRequiredService(eventHandlerType.MakeGenericType(eventType, responseType));
257+
Type eventHandlerType = typeof(IEventResponseHandler<,>).MakeGenericType(eventType, responseType);
258+
dynamic eventHandler = _serviceProvider.GetRequiredService(eventHandlerType);
258259
if (eventHandler == null)
259260
{
260261
throw new InvalidOperationException(eventHandler.GetType().Name);
261262
}
262-
Type concreteType = eventHandlerType.MakeGenericType(eventType, responseType);
263+
Type concreteType = eventHandlerType;
263264
var r = (object)await concreteType.GetMethod("HandleAsync").Invoke(
264265
eventHandler,
265266
new object[] {
@@ -277,6 +278,23 @@ private async Task<string> ProcessEventAsync(string body, Type eventType, Type r
277278
/// <returns></returns>
278279
private async Task ProcessEventAsync(string body, Type eventType, BasicDeliverEventArgs args)
279280
{
281+
//Type eventHandlerType = typeof(IEventHandler<>).MakeGenericType(eventType);
282+
//dynamic eventHandler = _serviceProvider.GetRequiredService(eventHandlerType);
283+
//if (eventHandler == null)
284+
//{
285+
// throw new InvalidOperationException(eventHandler.GetType().Name);
286+
//}
287+
////IEventHandler<RabbitMQ.EventBus.AspNetCore.Simple.Controllers.MessageBody>
288+
289+
//object logger = _serviceProvider.GetRequiredService(typeof(ILogger<>).MakeGenericType(eventType));
290+
//Type concreteType = eventHandlerType.MakeGenericType(eventType);
291+
//await (Task)concreteType.GetMethod(nameof(IEventHandler<IEvent>.Handle)).Invoke(
292+
// eventHandler,
293+
// new object[] {
294+
// Activator.CreateInstance(typeof(HandlerEventArgs<>).MakeGenericType(eventType), new object[] { body, args.Redelivered, args.Exchange, args.RoutingKey, logger })
295+
// });
296+
297+
280298
using var scope = _serviceProvider.CreateScope();
281299
foreach (Type eventHandleType in typeof(IEventHandler<>).GetMakeGenericType(eventType))
282300
{
Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
/// <summary>
1+
using Microsoft.AspNetCore.Builder;
2+
using Microsoft.Extensions.DependencyInjection;
3+
using System;
4+
/// <summary>
25
///
36
/// </summary>
47
public static class ServiceCollectionExtensions
@@ -15,7 +18,7 @@ public static class ServiceCollectionExtensions
1518
/// <param name="eventBusOptionAction"></param>
1619
/// <param name="moduleOptions"></param>
1720
/// <returns></returns>
18-
public static IServiceProvider AddRabbitMQEventBus(this IServiceCollection services, string endpoint, int port, string username, string password, string visualHost, Action<RabbitMQEventBusConnectionConfigurationBuild> eventBusOptionAction, Action<RabbitMQEventBusModuleOption> moduleOptions = null)
21+
public static IServiceCollection AddRabbitMQEventBus(this IServiceCollection services, string endpoint, int port, string username, string password, string visualHost, Action<RabbitMQEventBusConnectionConfigurationBuild> eventBusOptionAction, Action<RabbitMQEventBusModuleOption> moduleOptions = null)
1922
=> AddRabbitMQEventBus(services, () => $"amqp://{username}:{password}@{endpoint}:{port}/{visualHost}", eventBusOptionAction, moduleOptions);
2023

2124
/// <summary>
@@ -25,7 +28,7 @@ public static IServiceProvider AddRabbitMQEventBus(this IServiceCollection servi
2528
/// <param name="connectionAction">使用匿名函数取得连接字符串,用来兼容使用Consul获取服务地址的情况</param>
2629
/// <param name="eventBusOptionAction"></param>
2730
/// <returns></returns>
28-
public static IServiceProvider AddRabbitMQEventBus(this IServiceCollection services, Func<string> connectionAction, Action<RabbitMQEventBusConnectionConfigurationBuild> eventBusOptionAction, Action<RabbitMQEventBusModuleOption> moduleOptions = null)
31+
public static IServiceCollection AddRabbitMQEventBus(this IServiceCollection services, Func<string> connectionAction, Action<RabbitMQEventBusConnectionConfigurationBuild> eventBusOptionAction, Action<RabbitMQEventBusModuleOption> moduleOptions = null)
2932
{
3033
RabbitMQEventBusConnectionConfiguration configuration = new();
3134
RabbitMQEventBusConnectionConfigurationBuild configurationBuild = new(configuration);
@@ -38,42 +41,42 @@ public static IServiceProvider AddRabbitMQEventBus(this IServiceCollection servi
3841
logger.LogInformation("RabbitMQ event bus connected.");
3942
return connection;
4043
});
44+
4145
services.TryAddSingleton<IRabbitMQEventBus>(options =>
4246
{
4347
IRabbitMQPersistentConnection rabbitMQPersistentConnection = options.GetRequiredService<IRabbitMQPersistentConnection>();
4448
ILogger<DefaultRabbitMQEventBusV2> logger = options.GetRequiredService<ILogger<DefaultRabbitMQEventBusV2>>();
4549
var eventBus = DefaultRabbitMQEventBusV2.CreateInstance(rabbitMQPersistentConnection, options, logger);
4650
return eventBus;
4751
});
48-
foreach (Type mType in typeof(IEvent).GetAssemblies())
52+
foreach (var (registerType, handlerType, eventType, responseType) in RabbitmqEventBusHandlers.RegisterEventResponseHandlers())
53+
{
54+
services.TryAddTransient(registerType, handlerType);
55+
}
56+
foreach (var (handlerType, eventType) in RabbitmqEventBusHandlers.RegisterEventHandlers())
4957
{
50-
foreach (Type hType in typeof(IEventHandler<>).GetMakeGenericType(mType))
51-
{
52-
services.TryAddTransient(hType);
53-
}
58+
services.TryAddTransient(handlerType);
5459
}
55-
var responseHandlers = services.RegisterEventResponseHandlers().ToList();
56-
var serviceProvider = services.BuildServiceProvider();
57-
var _logger = serviceProvider.GetRequiredService<ILogger<DefaultRabbitMQEventBusV2>>();
58-
var rmqeV2 = serviceProvider.GetService<IRabbitMQEventBus>();
59-
foreach (var (registerType, handlerType, eventType, responseType) in responseHandlers)
60+
return services;
61+
}
62+
/// <summary>
63+
///
64+
/// </summary>
65+
/// <param name="app"></param>
66+
public static void UseRabbitmqEventBus(this IApplicationBuilder app)
67+
{
68+
IRabbitMQEventBus rmqeV2 = app.ApplicationServices.GetRequiredService<IRabbitMQEventBus>();
69+
var _logger = app.ApplicationServices.GetRequiredService<ILogger<DefaultRabbitMQEventBusV2>>();
70+
foreach (var (registerType, handlerType, eventType, responseType) in RabbitmqEventBusHandlers.RegisterEventResponseHandlers())
6071
{
6172
rmqeV2.Subscribe(eventType, responseType);
6273
_logger.LogInformation($"subscribe:\t{eventType}\t=>\t{handlerType}<{eventType.Name},{responseType.Name}>\t return Type : \t{responseType}");
6374
}
64-
foreach (Type mType in typeof(IEvent).GetAssemblies())
75+
foreach (var (handlerType, eventType) in RabbitmqEventBusHandlers.RegisterEventHandlers())
6576
{
66-
var handlesAny = typeof(IEventHandler<>).GetMakeGenericType(mType);
67-
if (handlesAny.Any())
68-
{
69-
rmqeV2.Subscribe(mType);
70-
foreach (var handler in handlesAny)
71-
{
72-
_logger.LogInformation($"subscribe:{mType}\t=>\t{handler}\t");
73-
}
74-
}
77+
rmqeV2.Subscribe(eventType);
78+
_logger.LogInformation($"subscribe:\t{eventType}\t=>\t{handlerType}<{eventType.Name}>");
7579
}
76-
return serviceProvider;
7780
}
7881
}
7982

src/RabbitMQ.EventBus.AspNetCore/Extensions/TypeExtensions.cs

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
namespace Microsoft.Extensions.DependencyInjection;
1+
using Microsoft.Extensions.DependencyInjection.Extensions;
2+
using RabbitMQ.EventBus.AspNetCore.Events;
3+
using System;
4+
using System.Data;
5+
6+
namespace Microsoft.Extensions.DependencyInjection;
27
/// <summary>
38
///
49
/// </summary>
@@ -23,26 +28,7 @@ public static IEnumerable<Type> GetMakeGenericType(this Type interfalceType, Typ
2328
{
2429
return AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(interfalceType.MakeGenericType(makeType))));
2530
}
26-
public static IEnumerable<(Type registerType, Type handlerType, Type eventType, Type responseType)> RegisterEventResponseHandlers(this IServiceCollection services)
27-
{
28-
foreach (var eventResponseHandler in AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.GetInterfaces().Any(x => x.IsGenericType && !x.IsGenericTypeDefinition && x.GetGenericTypeDefinition() == typeof(IEventResponseHandler<,>))))
29-
{
30-
var interfaces = eventResponseHandler.GetInterfaces()
31-
.Where(x =>
32-
x.IsGenericType &&
33-
!x.IsGenericTypeDefinition &&
34-
x.GetGenericTypeDefinition() == typeof(IEventResponseHandler<,>)
35-
);
36-
foreach (var iface in interfaces)
37-
{
38-
var eventResponseHandleArgs = iface.GetGenericArguments();
39-
var eventType = eventResponseHandleArgs[0];
40-
var responseType = eventResponseHandleArgs[1];
41-
services.TryAddTransient(iface, eventResponseHandler);
42-
yield return (iface, eventResponseHandler, eventType, responseType);
43-
}
44-
}
45-
}
31+
4632
public static bool IsNullOrWhiteSpace(this string source)
4733
{
4834
return string.IsNullOrWhiteSpace(source);

src/RabbitMQ.EventBus.AspNetCore/Factories/IRabbitMQPersistentConnection.cs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,58 @@ public interface IRabbitMQPersistentConnection : IDisposable
2626
/// </summary>
2727
/// <returns></returns>
2828
IModel CreateModel();
29+
}
30+
31+
public static class RabbitmqEventBusHandlers
32+
{
33+
34+
public static IEnumerable<(Type registerType, Type handlerType, Type eventType, Type responseType)> RegisterEventResponseHandlers()
35+
{
36+
foreach (var eventResponseHandler in AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.GetInterfaces().Any(x => x.IsGenericType && !x.IsGenericTypeDefinition && x.GetGenericTypeDefinition() == typeof(IEventResponseHandler<,>))))
37+
{
38+
var interfaces = eventResponseHandler.GetInterfaces()
39+
.Where(x =>
40+
x.IsGenericType &&
41+
!x.IsGenericTypeDefinition &&
42+
x.GetGenericTypeDefinition() == typeof(IEventResponseHandler<,>)
43+
);
44+
foreach (var iface in interfaces)
45+
{
46+
var eventResponseHandleArgs = iface.GetGenericArguments();
47+
var eventType = eventResponseHandleArgs[0];
48+
var responseType = eventResponseHandleArgs[1];
49+
yield return (iface, eventResponseHandler, eventType, responseType);
50+
}
51+
}
52+
}
53+
54+
55+
public static IEnumerable<(Type handlerType, Type eventType)> RegisterEventHandlers()
56+
{
57+
foreach (Type mType in typeof(IEvent).GetAssemblies())
58+
{
59+
foreach (Type hType in typeof(IEventHandler<>).GetMakeGenericType(mType))
60+
{
61+
yield return (hType, mType);
62+
}
63+
}
64+
65+
//foreach (var eventHandler in AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
66+
// .Where(t => t.GetInterfaces().Any(x => x.IsGenericType && !x.IsGenericTypeDefinition && x.GetGenericTypeDefinition() == typeof(IEventHandler<>))))
67+
//{
68+
// var interfaces = eventHandler.GetInterfaces()
69+
// .Where(x =>
70+
// x.IsGenericType &&
71+
// !x.IsGenericTypeDefinition &&
72+
// x.GetGenericTypeDefinition() == typeof(IEventHandler<>)
73+
// );
74+
// foreach (var iface in interfaces)
75+
// {
76+
// var eventType = iface.GetGenericArguments().FirstOrDefault();
77+
// services.TryAddTransient(eventType);
78+
// services.TryAddTransient(typeof(IEventHandler<>).MakeGenericType(eventType), eventHandler);
79+
// yield return (iface, eventHandler, eventType);
80+
// }
81+
//}
82+
}
2983
}

src/RabbitMQ.EventBus.AspNetCore/RabbitMQ.EventBus.AspNetCore.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
</PropertyGroup>
2424

2525
<ItemGroup>
26+
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
2627
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
2728
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
2829
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.1" />

0 commit comments

Comments
 (0)