Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pref: Modify and set the global Assembly collection and Remove GetAllEventTypes method #398

Merged
merged 4 commits into from
Jan 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/BuildingBlocks/Data/Masa.BuildingBlocks.Data/MasaApp.cs
Original file line number Diff line number Diff line change
@@ -19,7 +19,7 @@ public static IServiceProvider RootServiceProvider

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

private static Assembly[]? Assemblies { get; set; }
private static IEnumerable<Assembly>? Assemblies { get; set; }

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

/// <summary>
/// Set the global Assembly collection (only if Assembly is not assigned a value)
/// </summary>
/// <param name="assemblies"></param>
public static void TrySetAssemblies(IEnumerable<Assembly> assemblies)
{
ArgumentNullException.ThrowIfNull(assemblies);

Assemblies ??= assemblies.ToArray();
}

/// <summary>
/// Set the global Assembly collection
/// </summary>
/// <param name="assemblies"></param>
public static void SetAssemblies(params Assembly[] assemblies)
=> Assemblies = assemblies;

public static Assembly[] GetAssemblies() => Assemblies ?? AppDomain.CurrentDomain.GetAssemblies();
/// <summary>
/// Set the global Assembly collection
/// </summary>
/// <param name="assemblies"></param>
public static void SetAssemblies(IEnumerable<Assembly> assemblies)
=> Assemblies = assemblies;

public static IEnumerable<Assembly> GetAssemblies() => Assemblies ?? AppDomain.CurrentDomain.GetAssemblies();

public static void TrySetJsonSerializerOptions(JsonSerializerOptions jsonSerializerOptions)
{
Original file line number Diff line number Diff line change
@@ -8,7 +8,5 @@ public interface IEventBus
Task PublishAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)
where TEvent : IEvent;

IEnumerable<Type> GetAllEventTypes();

Task CommitAsync(CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ public class CallerOptions

public IServiceCollection Services { get; }

private Assembly[]? _assemblies;
private IEnumerable<Assembly>? _assemblies;

public Assembly[] Assemblies
public IEnumerable<Assembly> Assemblies
{
get => _assemblies ?? MasaApp.GetAssemblies();
set
Original file line number Diff line number Diff line change
@@ -688,7 +688,7 @@ public void TestPublish(string channel, string key, string value)
option.Value = value;
});

Thread.Sleep(3000);
Task.Delay(3000).ConfigureAwait(false).GetAwaiter().GetResult();
Assert.IsTrue(timer == 1);
}

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

Thread.Sleep(3000);
await Task.Delay(3000);
Assert.IsTrue(timer == 1);
}

Original file line number Diff line number Diff line change
@@ -116,7 +116,7 @@ public void TestAddStackExchangeRedisCacheByAppsettings()
}
}));

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

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

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

Thread.Sleep(3000);
Task.Delay(3000).ConfigureAwait(false).GetAwaiter().GetResult();

distributedCacheClient.Remove(key);
}
Original file line number Diff line number Diff line change
@@ -68,7 +68,7 @@ public void TestGetAndSubscribe()
Assert.AreEqual(null, value);

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

CombinedCacheEntryOptions? combinedCacheEntryOptions = null;
await _multilevelCacheClient.SetAsync(key, "test2", combinedCacheEntryOptions);
Thread.Sleep(3000);
await Task.Delay(3000);
Assert.AreEqual("test2", value);
await _multilevelCacheClient.RemoveAsync<string>(key);
}
Original file line number Diff line number Diff line change
@@ -234,7 +234,7 @@ await File.WriteAllTextAsync(Path.Combine(rootPath, "appsettings.json"),
}
}
}));
Thread.Sleep(2000);
await Task.Delay(2000);

subscribeKeyPrefix =
(string)multilevelCacheClientType.GetField(
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ public static void UseMasaOptions(this IMasaConfigurationBuilder builder, Action
builder.AddRelations(relation.Relations.ToArray());
}

internal static void AutoMapping(this MasaConfigurationBuilder builder, params Assembly[] assemblies)
internal static void AutoMapping(this MasaConfigurationBuilder builder, IEnumerable<Assembly> assemblies)
{
var optionTypes = assemblies
.SelectMany(assembly => assembly.GetTypes())
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ namespace Masa.Contrib.Configuration;

public class ConfigurationOptions
{
public Assembly[] Assemblies { get; set; }
public IEnumerable<Assembly> Assemblies { get; set; }

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

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

Thread.Sleep(2000);
await Task.Delay(2000);

var option = serviceProvider.GetRequiredService<IOptionsMonitor<RedisOptions>>();
Assert.IsTrue(option.CurrentValue.Ip == "" && option.CurrentValue.Port == 6379);

Original file line number Diff line number Diff line change
@@ -8,20 +8,17 @@ public class DomainEventBus : IDomainEventBus
private readonly IEventBus _eventBus;
private readonly IIntegrationEventBus _integrationEventBus;
private readonly IUnitOfWork _unitOfWork;
private readonly DispatcherOptions _options;

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

public DomainEventBus(
IEventBus eventBus,
IIntegrationEventBus integrationEventBus,
IUnitOfWork unitOfWork,
IOptions<DispatcherOptions> options)
IUnitOfWork unitOfWork)
{
_eventBus = eventBus;
_integrationEventBus = integrationEventBus;
_unitOfWork = unitOfWork;
_options = options.Value;
}

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

public async Task CommitAsync(CancellationToken cancellationToken = default)
=> await _unitOfWork.CommitAsync(cancellationToken);

public IEnumerable<Type> GetAllEventTypes() => _options.AllEventTypes.Concat(_eventBus.GetAllEventTypes()).Distinct();
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace Masa.Contrib.Ddd.Domain;
// ReSharper disable once CheckNamespace

namespace Masa.BuildingBlocks.Ddd.Domain.Services;

public class DomainService : IDomainService
{
Original file line number Diff line number Diff line change
@@ -17,8 +17,6 @@ private bool IsAggregateRootEntity(Type type)

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

internal List<Type> AllEventTypes { get; private set; }

internal List<Type> AllDomainServiceTypes { get; private set; }

internal List<Type> AllAggregateRootTypes { get; private set; }
@@ -30,7 +28,6 @@ public DispatcherOptions(IServiceCollection services, Assembly[] assemblies)
{
Assemblies = assemblies;
Types = assemblies.SelectMany(assembly => assembly.GetTypes());
AllEventTypes = GetTypes(typeof(IEvent)).ToList();
AllDomainServiceTypes = GetTypes(typeof(DomainService)).ToList();
AllAggregateRootTypes = GetTypes(typeof(IAggregateRoot)).Where(IsAggregateRootEntity).ToList();
}
Original file line number Diff line number Diff line change
@@ -18,15 +18,9 @@ public void Test()
_integrationEventBus = new();
_integrationEventBus.Setup(bus => bus.PublishAsync(It.IsAny<IIntegrationEvent>(), default)).Verifiable();
Mock<IUnitOfWork> unitOfWork = new();
IOptions<DispatcherOptions> options =
Microsoft.Extensions.Options.Options.Create(
new DispatcherOptions(
new ServiceCollection(),
AppDomain.CurrentDomain.GetAssemblies()));
_domainEventBus = new DomainEventBus(_eventBus.Object,
_integrationEventBus.Object,
unitOfWork.Object,
options
unitOfWork.Object
);
}

Original file line number Diff line number Diff line change
@@ -7,7 +7,6 @@ namespace Microsoft.Extensions.DependencyInjection;

public static class ServiceCollectionExtensions
{

#region Obsolete

[Obsolete("Use AddIntegrationEventBus instead")]
@@ -20,15 +19,15 @@ public static IServiceCollection AddDaprEventBus<TIntegrationEventLogService>(
[Obsolete("Use AddIntegrationEventBus instead")]
public static IServiceCollection AddDaprEventBus<TIntegrationEventLogService>(
this IServiceCollection services,
Assembly[] assemblies,
IEnumerable<Assembly> assemblies,
Action<DaprIntegrationEventOptions>? options = null,
Action<DaprClientBuilder>? builder = null)
where TIntegrationEventLogService : class, IIntegrationEventLogService
=> services.TryAddDaprEventBus<TIntegrationEventLogService>(assemblies, options, builder);

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

#endregion

}
Original file line number Diff line number Diff line change
@@ -5,18 +5,17 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents.EventLogs.EFCore;

public class IntegrationEventLogService : IIntegrationEventLogService
{
private readonly IEnumerable<Type> _integrationEventTypes;
private readonly IntegrationEventLogContext _eventLogContext;
private readonly IServiceProvider _serviceProvider;
private readonly Logger<IntegrationEventLogService>? _logger;
private IEnumerable<Type>? _eventTypes;
private readonly ILogger<IntegrationEventLogService>? _logger;

public IntegrationEventLogService(
IEnumerable<Type> integrationEventTypes,
IntegrationEventLogContext eventLogContext,
IServiceProvider serviceProvider,
Logger<IntegrationEventLogService>? logger = null)
ILogger<IntegrationEventLogService>? logger = null)
{
_integrationEventTypes = integrationEventTypes;
_eventLogContext = eventLogContext;
_serviceProvider = serviceProvider;
_logger = logger;
}

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

if (result.Any())
{
_eventTypes ??= _serviceProvider.GetRequiredService<IIntegrationEventBus>().GetAllEventTypes()
.Where(type => typeof(IIntegrationEvent).IsAssignableFrom(type));

return result.OrderBy(e => e.CreationTime)
.Select(e => e.DeserializeJsonContent(_eventTypes.First(t => t.Name == e.EventTypeShortName)));
.Select(e => e.DeserializeJsonContent(_integrationEventTypes.First(t => t.Name == e.EventTypeShortName)));
}

return result;
@@ -72,11 +68,8 @@ public async Task<IEnumerable<IntegrationEventLog>> RetrieveEventLogsPendingToPu
.ToListAsync(cancellationToken);
if (result.Any())
{
_eventTypes ??= _serviceProvider.GetRequiredService<IIntegrationEventBus>().GetAllEventTypes()
.Where(type => typeof(IIntegrationEvent).IsAssignableFrom(type));

return result.OrderBy(e => e.CreationTime)
.Select(e => e.DeserializeJsonContent(_eventTypes.First(t => t.Name == e.EventTypeShortName)));
.Select(e => e.DeserializeJsonContent(_integrationEventTypes.First(t => t.Name == e.EventTypeShortName)));
}

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

if (_eventLogContext.DbContext.ChangeTracker.QueryTrackingBehavior != QueryTrackingBehavior.TrackAll)
{
Original file line number Diff line number Diff line change
@@ -19,13 +19,17 @@ public static IIntegrationEventOptions UseEventLog<TDbContext>(
this IIntegrationEventOptions options,
bool disableEntityTypeConfiguration = false) where TDbContext : MasaDbContext, IMasaDbContext
{
MasaArgumentException.ThrowIfNull(options.Services, nameof(options.Services));
MasaArgumentException.ThrowIfNull(options.Services);

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

options.Services.AddSingleton<EventLogProvider>();

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

//Add local message table model mapping
if (!disableEntityTypeConfiguration)
Original file line number Diff line number Diff line change
@@ -26,14 +26,14 @@ public static IServiceCollection AddIntegrationEventBus<TIntegrationEventLogServ

public static IServiceCollection AddIntegrationEventBus<TIntegrationEventLogService>(
this IServiceCollection services,
Assembly[] assemblies,
IEnumerable<Assembly> assemblies,
Action<IntegrationEventOptions>? options = null)
where TIntegrationEventLogService : class, IIntegrationEventLogService
=> services.TryAddIntegrationEventBus<TIntegrationEventLogService>(assemblies, options);

internal static IServiceCollection TryAddIntegrationEventBus<TIntegrationEventLogService>(
this IServiceCollection services,
Assembly[] assemblies,
IEnumerable<Assembly> assemblies,
Action<IntegrationEventOptions>? options)
where TIntegrationEventLogService : class, IIntegrationEventLogService
=> services.TryAddIntegrationEventBus(
Original file line number Diff line number Diff line change
@@ -5,23 +5,20 @@ namespace Masa.Contrib.Dispatcher.IntegrationEvents;

public class IntegrationEventBus : IIntegrationEventBus
{
private readonly IntegrationEventOptions _dispatcherOptions;
private readonly IPublisher _publisher;
private readonly ILogger<IntegrationEventBus>? _logger;
private readonly IIntegrationEventLogService? _eventLogService;
private readonly IOptionsMonitor<MasaAppConfigureOptions>? _masaAppConfigureOptions;
private readonly IEventBus? _eventBus;
private readonly IUnitOfWork? _unitOfWork;

public IntegrationEventBus(IOptions<IntegrationEventOptions> options,
IPublisher publisher,
public IntegrationEventBus(IPublisher publisher,
IIntegrationEventLogService? eventLogService = null,
IOptionsMonitor<MasaAppConfigureOptions>? masaAppConfigureOptions = null,
ILogger<IntegrationEventBus>? logger = null,
IEventBus? eventBus = null,
IUnitOfWork? unitOfWork = null)
{
_dispatcherOptions = options.Value;
_publisher = publisher;
_eventLogService = eventLogService;
_masaAppConfigureOptions = masaAppConfigureOptions;
@@ -30,11 +27,6 @@ public IntegrationEventBus(IOptions<IntegrationEventOptions> options,
_unitOfWork = unitOfWork;
}

public IEnumerable<Type> GetAllEventTypes() =>
_eventBus == null
? _dispatcherOptions.AllEventTypes
: _dispatcherOptions.AllEventTypes.Concat(_eventBus.GetAllEventTypes()).Distinct();

public async Task PublishAsync<TEvent>(TEvent @event, CancellationToken cancellationToken = default)
where TEvent : IEvent
{
Loading