Skip to content

Commit af133e1

Browse files
authored
pref: Modify and set the global Assembly collection and Remove GetAllEventTypes method (#398)
* pref: Optimize MasaApp * pref(EventBus): Remove GetAllEventTypes method * fix: fix code smell * test: Remove Thread.Sleep
1 parent ac7c7d5 commit af133e1

File tree

26 files changed

+304
-458
lines changed

26 files changed

+304
-458
lines changed

src/BuildingBlocks/Data/Masa.BuildingBlocks.Data/MasaApp.cs

+20-2
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ public static IServiceProvider RootServiceProvider
1919

2020
private static IServiceCollection Services { get; set; } = new ServiceCollection();
2121

22-
private static Assembly[]? Assemblies { get; set; }
22+
private static IEnumerable<Assembly>? Assemblies { get; set; }
2323

2424
/// <summary>
2525
/// Global JsonSerializerOptions configuration
@@ -66,14 +66,32 @@ public static void TrySetAssemblies(params Assembly[] assemblies)
6666
Assemblies ??= assemblies;
6767
}
6868

69+
/// <summary>
70+
/// Set the global Assembly collection (only if Assembly is not assigned a value)
71+
/// </summary>
72+
/// <param name="assemblies"></param>
73+
public static void TrySetAssemblies(IEnumerable<Assembly> assemblies)
74+
{
75+
ArgumentNullException.ThrowIfNull(assemblies);
76+
77+
Assemblies ??= assemblies.ToArray();
78+
}
79+
6980
/// <summary>
7081
/// Set the global Assembly collection
7182
/// </summary>
7283
/// <param name="assemblies"></param>
7384
public static void SetAssemblies(params Assembly[] assemblies)
7485
=> Assemblies = assemblies;
7586

76-
public static Assembly[] GetAssemblies() => Assemblies ?? AppDomain.CurrentDomain.GetAssemblies();
87+
/// <summary>
88+
/// Set the global Assembly collection
89+
/// </summary>
90+
/// <param name="assemblies"></param>
91+
public static void SetAssemblies(IEnumerable<Assembly> assemblies)
92+
=> Assemblies = assemblies;
93+
94+
public static IEnumerable<Assembly> GetAssemblies() => Assemblies ?? AppDomain.CurrentDomain.GetAssemblies();
7795

7896
public static void TrySetJsonSerializerOptions(JsonSerializerOptions jsonSerializerOptions)
7997
{

src/BuildingBlocks/Dispatcher/Masa.BuildingBlocks.Dispatcher.Events/IEventBus.cs

-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,5 @@ public interface IEventBus
88
Task PublishAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)
99
where TEvent : IEvent;
1010

11-
IEnumerable<Type> GetAllEventTypes();
12-
1311
Task CommitAsync(CancellationToken cancellationToken = default);
1412
}

src/BuildingBlocks/Service/Masa.BuildingBlocks.Service.Caller/Options/CallerOptions.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ public class CallerOptions
1111

1212
public IServiceCollection Services { get; }
1313

14-
private Assembly[]? _assemblies;
14+
private IEnumerable<Assembly>? _assemblies;
1515

16-
public Assembly[] Assemblies
16+
public IEnumerable<Assembly> Assemblies
1717
{
1818
get => _assemblies ?? MasaApp.GetAssemblies();
1919
set

src/Contrib/Caching/Distributed/Tests/Masa.Contrib.Caching.Distributed.StackExchangeRedis.Tests/DistributedCacheClientTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -688,7 +688,7 @@ public void TestPublish(string channel, string key, string value)
688688
option.Value = value;
689689
});
690690

691-
Thread.Sleep(3000);
691+
Task.Delay(3000).ConfigureAwait(false).GetAwaiter().GetResult();
692692
Assert.IsTrue(timer == 1);
693693
}
694694

@@ -713,7 +713,7 @@ await _distributedCacheClient.PublishAsync(channel, option =>
713713
option.Value = value;
714714
});
715715

716-
Thread.Sleep(3000);
716+
await Task.Delay(3000);
717717
Assert.IsTrue(timer == 1);
718718
}
719719

src/Contrib/Caching/Distributed/Tests/Masa.Contrib.Caching.Distributed.StackExchangeRedis.Tests/StackExchangeRedisCacheTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ public void TestAddStackExchangeRedisCacheByAppsettings()
116116
}
117117
}));
118118

119-
Thread.Sleep(3000);
119+
Task.Delay(3000).ConfigureAwait(false).GetAwaiter().GetResult();
120120
distributedCacheClient = serviceProvider.GetRequiredService<IDistributedCacheClientFactory>().Create();
121121

122122
var exist = distributedCacheClient.Exists(key);
@@ -125,7 +125,7 @@ public void TestAddStackExchangeRedisCacheByAppsettings()
125125

126126
File.WriteAllText(Path.Combine(Path.Combine(rootPath, "appsettings.json")), oldContent);
127127

128-
Thread.Sleep(3000);
128+
Task.Delay(3000).ConfigureAwait(false).GetAwaiter().GetResult();
129129

130130
distributedCacheClient.Remove(key);
131131
}

src/Contrib/Caching/Masa.Contrib.Caching.MultilevelCache.Tests/MultilevelCacheClientTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ public void TestGetAndSubscribe()
6868
Assert.AreEqual(null, value);
6969

7070
_multilevelCacheClient.Set(key, "test2");
71-
Thread.Sleep(3000);
71+
Task.Delay(3000).ConfigureAwait(false).GetAwaiter().GetResult();
7272
Assert.AreEqual("test2", value);
7373
_multilevelCacheClient.Remove<string>(key);
7474
}
@@ -85,7 +85,7 @@ public async Task TestGetAndSubscribeAsync()
8585

8686
CombinedCacheEntryOptions? combinedCacheEntryOptions = null;
8787
await _multilevelCacheClient.SetAsync(key, "test2", combinedCacheEntryOptions);
88-
Thread.Sleep(3000);
88+
await Task.Delay(3000);
8989
Assert.AreEqual("test2", value);
9090
await _multilevelCacheClient.RemoveAsync<string>(key);
9191
}

src/Contrib/Caching/Masa.Contrib.Caching.MultilevelCache.Tests/MultilevelCacheTest.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ await File.WriteAllTextAsync(Path.Combine(rootPath, "appsettings.json"),
234234
}
235235
}
236236
}));
237-
Thread.Sleep(2000);
237+
await Task.Delay(2000);
238238

239239
subscribeKeyPrefix =
240240
(string)multilevelCacheClientType.GetField(

src/Contrib/Configuration/Masa.Contrib.Configuration/Extensions/MasaConfigurationBuilderExtensions.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public static void UseMasaOptions(this IMasaConfigurationBuilder builder, Action
1414
builder.AddRelations(relation.Relations.ToArray());
1515
}
1616

17-
internal static void AutoMapping(this MasaConfigurationBuilder builder, params Assembly[] assemblies)
17+
internal static void AutoMapping(this MasaConfigurationBuilder builder, IEnumerable<Assembly> assemblies)
1818
{
1919
var optionTypes = assemblies
2020
.SelectMany(assembly => assembly.GetTypes())

src/Contrib/Configuration/Masa.Contrib.Configuration/Options/ConfigurationOptions.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace Masa.Contrib.Configuration;
77

88
public class ConfigurationOptions
99
{
10-
public Assembly[] Assemblies { get; set; }
10+
public IEnumerable<Assembly> Assemblies { get; set; }
1111

1212
public List<Type> ExcludeConfigurationSourceTypes { get; set; }
1313

src/Contrib/Configuration/Tests/Masa.Contrib.Configuration.Tests/ConfigurationTest.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,8 @@ public async Task TestConfigurationChangeShouldReturnNameEmpty()
212212
await File.WriteAllTextAsync(Path.Combine(rootPath, "customAppConfig.json"),
213213
System.Text.Json.JsonSerializer.Serialize(new { RedisOptions = newRedisOption }));
214214

215-
Thread.Sleep(2000);
215+
await Task.Delay(2000);
216+
216217
var option = serviceProvider.GetRequiredService<IOptionsMonitor<RedisOptions>>();
217218
Assert.IsTrue(option.CurrentValue.Ip == "" && option.CurrentValue.Port == 6379);
218219

src/Contrib/Ddd/Domain/Masa.Contrib.Ddd.Domain/DomainEventBus.cs

+1-6
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,17 @@ public class DomainEventBus : IDomainEventBus
88
private readonly IEventBus _eventBus;
99
private readonly IIntegrationEventBus _integrationEventBus;
1010
private readonly IUnitOfWork _unitOfWork;
11-
private readonly DispatcherOptions _options;
1211

1312
private readonly ConcurrentQueue<IDomainEvent> _eventQueue = new();
1413

1514
public DomainEventBus(
1615
IEventBus eventBus,
1716
IIntegrationEventBus integrationEventBus,
18-
IUnitOfWork unitOfWork,
19-
IOptions<DispatcherOptions> options)
17+
IUnitOfWork unitOfWork)
2018
{
2119
_eventBus = eventBus;
2220
_integrationEventBus = integrationEventBus;
2321
_unitOfWork = unitOfWork;
24-
_options = options.Value;
2522
}
2623

2724
public async Task PublishAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default) where TEvent : IEvent
@@ -74,6 +71,4 @@ public Task<bool> AnyQueueAsync()
7471

7572
public async Task CommitAsync(CancellationToken cancellationToken = default)
7673
=> await _unitOfWork.CommitAsync(cancellationToken);
77-
78-
public IEnumerable<Type> GetAllEventTypes() => _options.AllEventTypes.Concat(_eventBus.GetAllEventTypes()).Distinct();
7974
}

src/Contrib/Ddd/Domain/Masa.Contrib.Ddd.Domain/DomainService.cs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
// Copyright (c) MASA Stack All rights reserved.
22
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
33

4-
namespace Masa.Contrib.Ddd.Domain;
4+
// ReSharper disable once CheckNamespace
5+
6+
namespace Masa.BuildingBlocks.Ddd.Domain.Services;
57

68
public class DomainService : IDomainService
79
{

src/Contrib/Ddd/Domain/Masa.Contrib.Ddd.Domain/Options/DispatcherOptions.cs

-3
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@ private bool IsAggregateRootEntity(Type type)
1717

1818
private IEnumerable<Type> GetTypes(Type type) => Types.Where(t => t.IsClass && type.IsAssignableFrom(t));
1919

20-
internal List<Type> AllEventTypes { get; private set; }
21-
2220
internal List<Type> AllDomainServiceTypes { get; private set; }
2321

2422
internal List<Type> AllAggregateRootTypes { get; private set; }
@@ -30,7 +28,6 @@ public DispatcherOptions(IServiceCollection services, Assembly[] assemblies)
3028
{
3129
Assemblies = assemblies;
3230
Types = assemblies.SelectMany(assembly => assembly.GetTypes());
33-
AllEventTypes = GetTypes(typeof(IEvent)).ToList();
3431
AllDomainServiceTypes = GetTypes(typeof(DomainService)).ToList();
3532
AllAggregateRootTypes = GetTypes(typeof(IAggregateRoot)).Where(IsAggregateRootEntity).ToList();
3633
}

src/Contrib/Ddd/Domain/Tests/Masa.Contrib.Ddd.Domain.Tests/DomainEventBusTest.cs

+1-7
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,9 @@ public void Test()
1818
_integrationEventBus = new();
1919
_integrationEventBus.Setup(bus => bus.PublishAsync(It.IsAny<IIntegrationEvent>(), default)).Verifiable();
2020
Mock<IUnitOfWork> unitOfWork = new();
21-
IOptions<DispatcherOptions> options =
22-
Microsoft.Extensions.Options.Options.Create(
23-
new DispatcherOptions(
24-
new ServiceCollection(),
25-
AppDomain.CurrentDomain.GetAssemblies()));
2621
_domainEventBus = new DomainEventBus(_eventBus.Object,
2722
_integrationEventBus.Object,
28-
unitOfWork.Object,
29-
options
23+
unitOfWork.Object
3024
);
3125
}
3226

src/Contrib/Dispatcher/IntegrationEvents/Masa.Contrib.Dispatcher.IntegrationEvents.Dapr/Extensions/ServiceCollectionExtensions.cs

+2-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ namespace Microsoft.Extensions.DependencyInjection;
77

88
public static class ServiceCollectionExtensions
99
{
10-
1110
#region Obsolete
1211

1312
[Obsolete("Use AddIntegrationEventBus instead")]
@@ -20,15 +19,15 @@ public static IServiceCollection AddDaprEventBus<TIntegrationEventLogService>(
2019
[Obsolete("Use AddIntegrationEventBus instead")]
2120
public static IServiceCollection AddDaprEventBus<TIntegrationEventLogService>(
2221
this IServiceCollection services,
23-
Assembly[] assemblies,
22+
IEnumerable<Assembly> assemblies,
2423
Action<DaprIntegrationEventOptions>? options = null,
2524
Action<DaprClientBuilder>? builder = null)
2625
where TIntegrationEventLogService : class, IIntegrationEventLogService
2726
=> services.TryAddDaprEventBus<TIntegrationEventLogService>(assemblies, options, builder);
2827

2928
internal static IServiceCollection TryAddDaprEventBus<TIntegrationEventLogService>(
3029
this IServiceCollection services,
31-
Assembly[] assemblies,
30+
IEnumerable<Assembly> assemblies,
3231
Action<DaprIntegrationEventOptions>? options,
3332
Action<DaprClientBuilder>? builder = null)
3433
where TIntegrationEventLogService : class, IIntegrationEventLogService
@@ -55,5 +54,4 @@ private sealed class IntegrationEventBusProvider
5554
}
5655

5756
#endregion
58-
5957
}

src/Contrib/Dispatcher/IntegrationEvents/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EFCore/IntegrationEventLogService.cs

+12-16
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,17 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EFCore;
55

66
public class IntegrationEventLogService : IIntegrationEventLogService
77
{
8+
private readonly IEnumerable<Type> _integrationEventTypes;
89
private readonly IntegrationEventLogContext _eventLogContext;
9-
private readonly IServiceProvider _serviceProvider;
10-
private readonly Logger<IntegrationEventLogService>? _logger;
11-
private IEnumerable<Type>? _eventTypes;
10+
private readonly ILogger<IntegrationEventLogService>? _logger;
1211

1312
public IntegrationEventLogService(
13+
IEnumerable<Type> integrationEventTypes,
1414
IntegrationEventLogContext eventLogContext,
15-
IServiceProvider serviceProvider,
16-
Logger<IntegrationEventLogService>? logger = null)
15+
ILogger<IntegrationEventLogService>? logger = null)
1716
{
17+
_integrationEventTypes = integrationEventTypes;
1818
_eventLogContext = eventLogContext;
19-
_serviceProvider = serviceProvider;
2019
_logger = logger;
2120
}
2221

@@ -45,11 +44,8 @@ public async Task<IEnumerable<IntegrationEventLog>> RetrieveEventLogsFailedToPub
4544

4645
if (result.Any())
4746
{
48-
_eventTypes ??= _serviceProvider.GetRequiredService<IIntegrationEventBus>().GetAllEventTypes()
49-
.Where(type => typeof(IIntegrationEvent).IsAssignableFrom(type));
50-
5147
return result.OrderBy(e => e.CreationTime)
52-
.Select(e => e.DeserializeJsonContent(_eventTypes.First(t => t.Name == e.EventTypeShortName)));
48+
.Select(e => e.DeserializeJsonContent(_integrationEventTypes.First(t => t.Name == e.EventTypeShortName)));
5349
}
5450

5551
return result;
@@ -72,11 +68,8 @@ public async Task<IEnumerable<IntegrationEventLog>> RetrieveEventLogsPendingToPu
7268
.ToListAsync(cancellationToken);
7369
if (result.Any())
7470
{
75-
_eventTypes ??= _serviceProvider.GetRequiredService<IIntegrationEventBus>().GetAllEventTypes()
76-
.Where(type => typeof(IIntegrationEvent).IsAssignableFrom(type));
77-
7871
return result.OrderBy(e => e.CreationTime)
79-
.Select(e => e.DeserializeJsonContent(_eventTypes.First(t => t.Name == e.EventTypeShortName)));
72+
.Select(e => e.DeserializeJsonContent(_integrationEventTypes.First(t => t.Name == e.EventTypeShortName)));
8073
}
8174

8275
return result;
@@ -157,8 +150,11 @@ public async Task DeleteExpiresAsync(DateTime expiresAt, int batchCount, Cancell
157150
{
158151
var eventLogs = _eventLogContext.EventLogs.Where(e => e.ModificationTime < expiresAt && e.State == IntegrationEventStates.Published)
159152
.OrderBy(e => e.CreationTime).Take(batchCount);
160-
_eventLogContext.EventLogs.RemoveRange(eventLogs);
161-
await _eventLogContext.DbContext.SaveChangesAsync(token);
153+
if (eventLogs.Any())
154+
{
155+
_eventLogContext.EventLogs.RemoveRange(eventLogs);
156+
await _eventLogContext.DbContext.SaveChangesAsync(token);
157+
}
162158

163159
if (_eventLogContext.DbContext.ChangeTracker.QueryTrackingBehavior != QueryTrackingBehavior.TrackAll)
164160
{

src/Contrib/Dispatcher/IntegrationEvents/Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EFCore/IntegrationEventOptionsExtensions.cs

+6-2
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,17 @@ public static IIntegrationEventOptions UseEventLog<TDbContext>(
1919
this IIntegrationEventOptions options,
2020
bool disableEntityTypeConfiguration = false) where TDbContext : MasaDbContext, IMasaDbContext
2121
{
22-
MasaArgumentException.ThrowIfNull(options.Services, nameof(options.Services));
22+
MasaArgumentException.ThrowIfNull(options.Services);
2323

2424
if (options.Services.Any(service => service.ImplementationType == typeof(EventLogProvider))) return options;
2525

2626
options.Services.AddSingleton<EventLogProvider>();
2727

28-
options.Services.TryAddScoped<IIntegrationEventLogService, IntegrationEventLogService>();
28+
var integrationEventTypes = options.Assemblies.SelectMany(assembly => assembly.GetTypes()).Where(type => type.IsClass &&typeof(IIntegrationEvent).IsAssignableFrom(type)).Distinct();
29+
options.Services.TryAddScoped<IIntegrationEventLogService>(serviceProvider => new IntegrationEventLogService(
30+
integrationEventTypes,
31+
serviceProvider.GetRequiredService<IntegrationEventLogContext>(),
32+
serviceProvider.GetService<ILogger<IntegrationEventLogService>>()));
2933

3034
//Add local message table model mapping
3135
if (!disableEntityTypeConfiguration)

src/Contrib/Dispatcher/IntegrationEvents/Masa.Contrib.Dispatcher.IntegrationEvents/Extensions/ServiceCollectionExtensions.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,14 @@ public static IServiceCollection AddIntegrationEventBus<TIntegrationEventLogServ
2626

2727
public static IServiceCollection AddIntegrationEventBus<TIntegrationEventLogService>(
2828
this IServiceCollection services,
29-
Assembly[] assemblies,
29+
IEnumerable<Assembly> assemblies,
3030
Action<IntegrationEventOptions>? options = null)
3131
where TIntegrationEventLogService : class, IIntegrationEventLogService
3232
=> services.TryAddIntegrationEventBus<TIntegrationEventLogService>(assemblies, options);
3333

3434
internal static IServiceCollection TryAddIntegrationEventBus<TIntegrationEventLogService>(
3535
this IServiceCollection services,
36-
Assembly[] assemblies,
36+
IEnumerable<Assembly> assemblies,
3737
Action<IntegrationEventOptions>? options)
3838
where TIntegrationEventLogService : class, IIntegrationEventLogService
3939
=> services.TryAddIntegrationEventBus(

src/Contrib/Dispatcher/IntegrationEvents/Masa.Contrib.Dispatcher.IntegrationEvents/IntegrationEventBus.cs

+1-9
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,20 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents;
55

66
public class IntegrationEventBus : IIntegrationEventBus
77
{
8-
private readonly IntegrationEventOptions _dispatcherOptions;
98
private readonly IPublisher _publisher;
109
private readonly ILogger<IntegrationEventBus>? _logger;
1110
private readonly IIntegrationEventLogService? _eventLogService;
1211
private readonly IOptionsMonitor<MasaAppConfigureOptions>? _masaAppConfigureOptions;
1312
private readonly IEventBus? _eventBus;
1413
private readonly IUnitOfWork? _unitOfWork;
1514

16-
public IntegrationEventBus(IOptions<IntegrationEventOptions> options,
17-
IPublisher publisher,
15+
public IntegrationEventBus(IPublisher publisher,
1816
IIntegrationEventLogService? eventLogService = null,
1917
IOptionsMonitor<MasaAppConfigureOptions>? masaAppConfigureOptions = null,
2018
ILogger<IntegrationEventBus>? logger = null,
2119
IEventBus? eventBus = null,
2220
IUnitOfWork? unitOfWork = null)
2321
{
24-
_dispatcherOptions = options.Value;
2522
_publisher = publisher;
2623
_eventLogService = eventLogService;
2724
_masaAppConfigureOptions = masaAppConfigureOptions;
@@ -30,11 +27,6 @@ public IntegrationEventBus(IOptions<IntegrationEventOptions> options,
3027
_unitOfWork = unitOfWork;
3128
}
3229

33-
public IEnumerable<Type> GetAllEventTypes() =>
34-
_eventBus == null
35-
? _dispatcherOptions.AllEventTypes
36-
: _dispatcherOptions.AllEventTypes.Concat(_eventBus.GetAllEventTypes()).Distinct();
37-
3830
public async Task PublishAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)
3931
where TEvent : IEvent
4032
{

0 commit comments

Comments
 (0)