Skip to content

Commit

Permalink
Packages update, cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
spetz committed Sep 12, 2022
1 parent 149e437 commit 05612a2
Show file tree
Hide file tree
Showing 18 changed files with 128 additions and 100 deletions.
6 changes: 6 additions & 0 deletions src/Modular.Abstractions/AppInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Modular.Abstractions;

public record AppInfo(string Name, string Version)
{
public override string ToString() => $"{Name} {Version}";
}
8 changes: 5 additions & 3 deletions src/Modular.Infrastructure/Api/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Modular.Infrastructure.Api;
Expand Down Expand Up @@ -39,12 +40,13 @@ private static TModel Bind<TModel, TProperty>(this TModel model, Expression<Func
return model;
}

public static IServiceCollection AddCorsPolicy(this IServiceCollection services)
public static IServiceCollection AddCorsPolicy(this IServiceCollection services, IConfiguration configuration)
{
var corsOptions = services.GetOptions<CorsOptions>("cors");
var section = configuration.GetSection("cors");
var corsOptions = section.GetOptions<CorsOptions>();
services.Configure<CorsOptions>(section);

return services
.AddSingleton(corsOptions)
.AddCors(cors =>
{
var allowedHeaders = corsOptions.AllowedHeaders ?? Enumerable.Empty<string>();
Expand Down
16 changes: 10 additions & 6 deletions src/Modular.Infrastructure/Auth/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Modular.Abstractions.Auth;
Expand All @@ -17,13 +18,18 @@ namespace Modular.Infrastructure.Auth;

public static class Extensions
{
private const string SectionName = "auth";
private const string AccessTokenCookieName = "__access-token";
private const string AuthorizationHeader = "authorization";

public static IServiceCollection AddAuth(this IServiceCollection services, IList<IModule> modules = null,
Action<JwtBearerOptions> optionsFactory = null)
public static IServiceCollection AddAuth(this IServiceCollection services, IConfiguration configuration,
IEnumerable<IModule> modules = null, Action<JwtBearerOptions> optionsFactory = null)
{
var options = services.GetOptions<AuthOptions>("auth");
var authSection = configuration.GetSection(SectionName);
var cookieSection = configuration.GetSection($"{SectionName}:cookie");
var options = authSection.GetOptions<AuthOptions>();
services.Configure<AuthOptions>(authSection);
services.Configure<AuthOptions.CookieOptions>(cookieSection);
services.AddSingleton<IAuthManager, AuthManager>();

if (options.AuthenticationDisabled)
Expand Down Expand Up @@ -124,8 +130,6 @@ public static IServiceCollection AddAuth(this IServiceCollection services, IList
optionsFactory?.Invoke(o);
});

services.AddSingleton(options);
services.AddSingleton(options.Cookie);
services.AddSingleton(tokenValidationParameters);

var policies = modules?.SelectMany(x => x.Policies ?? Enumerable.Empty<string>()) ??
Expand Down Expand Up @@ -154,7 +158,7 @@ public static IApplicationBuilder UseAuth(this IApplicationBuilder app)
if (ctx.Request.Cookies.ContainsKey(AccessTokenCookieName))
{
var authenticateResult = await ctx.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
if (authenticateResult.Succeeded && authenticateResult.Principal is not null)
if (authenticateResult.Succeeded)
{
ctx.User = authenticateResult.Principal;
}
Expand Down
9 changes: 6 additions & 3 deletions src/Modular.Infrastructure/Cache/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;

namespace Modular.Infrastructure.Cache;

public static class Extensions
{
public static IServiceCollection AddRedisCache(this IServiceCollection services)
public static IServiceCollection AddRedisCache(this IServiceCollection services, IConfiguration configuration)
{
var options = services.GetOptions<RedisOptions>("redis");
var section = configuration.GetSection("redis");
var options = section.GetOptions<RedisOptions>();
services.Configure<RedisOptions>(section);
services.AddStackExchangeRedisCache(o => o.Configuration = options.ConnectionString);
services.AddScoped<ICache, RedisCache>();
services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(options.ConnectionString));
Expand Down
55 changes: 28 additions & 27 deletions src/Modular.Infrastructure/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Modular.Abstractions;
using Modular.Abstractions.Dispatchers;
using Modular.Abstractions.Modules;
using Modular.Abstractions.Storage;
Expand All @@ -35,33 +36,30 @@ namespace Modular.Infrastructure;

public static class Extensions
{
private const string AppSectionName = "app";
private const string CorrelationIdKey = "correlation-id";

public static IServiceCollection AddInitializer<T>(this IServiceCollection services) where T : class, IInitializer
=> services.AddTransient<IInitializer, T>();

public static IServiceCollection AddModularInfrastructure(this IServiceCollection services,
IList<Assembly> assemblies, IList<IModule> modules)
IConfiguration configuration, IList<Assembly> assemblies, IList<IModule> modules)
{
var disabledModules = new List<string>();
using (var serviceProvider = services.BuildServiceProvider())
foreach (var (key, value) in configuration.AsEnumerable())
{
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
foreach (var (key, value) in configuration.AsEnumerable())
if (!key.Contains(":module:enabled"))
{
if (!key.Contains(":module:enabled"))
{
continue;
}
continue;
}

if (!bool.Parse(value))
{
disabledModules.Add(key.Split(":")[0]);
}
if (!bool.Parse(value))
{
disabledModules.Add(key.Split(":")[0]);
}
}

services.AddCorsPolicy();
services.AddCorsPolicy(configuration);
services.AddSwaggerGen(swagger =>
{
swagger.EnableAnnotations();
Expand All @@ -73,8 +71,12 @@ public static IServiceCollection AddModularInfrastructure(this IServiceCollectio
});
});

var appOptions = services.GetOptions<AppOptions>("app");
services.AddSingleton(appOptions);
var appOptionsSection = configuration.GetSection(AppSectionName);
services.Configure<AppOptions>(appOptionsSection);

var appOptions = configuration.GetAppOptions();
var appInfo = new AppInfo(appOptions.Name, appOptions.Version);
services.AddSingleton(appInfo);

services.AddMemoryCache();
services.AddHttpClient();
Expand All @@ -83,16 +85,16 @@ public static IServiceCollection AddModularInfrastructure(this IServiceCollectio
services.AddSingleton<IJsonSerializer, SystemTextJsonSerializer>();
services.AddModuleInfo(modules);
services.AddModuleRequests(assemblies);
services.AddAuth(modules);
services.AddAuth(configuration, modules);
services.AddErrorHandling();
services.AddContext();
services.AddCommands(assemblies);
services.AddQueries(assemblies);
services.AddEvents(assemblies);
services.AddDomainEvents(assemblies);
services.AddMessaging();
services.AddSecurity();
services.AddOutbox();
services.AddMessaging(configuration);
services.AddSecurity(configuration);
services.AddOutbox(configuration);
services.AddSingleton<IClock, UtcClock>();
services.AddSingleton<IDispatcher, InMemoryDispatcher>();
services.AddControllers()
Expand Down Expand Up @@ -142,17 +144,16 @@ public static IApplicationBuilder UseModularInfrastructure(this IApplicationBuil
return app;
}

public static T GetOptions<T>(this IServiceCollection services, string sectionName) where T : new()
{
using var serviceProvider = services.BuildServiceProvider();
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
return configuration.GetOptions<T>(sectionName);
}

public static AppOptions GetAppOptions(this IConfiguration configuration)
=> configuration.GetOptions<AppOptions>(AppSectionName);

public static T GetOptions<T>(this IConfiguration configuration, string sectionName) where T : new()
=> configuration.GetSection(sectionName).GetOptions<T>();

public static T GetOptions<T>(this IConfigurationSection section) where T : new()
{
var options = new T();
configuration.GetSection(sectionName).Bind(options);
section.Bind(options);
return options;
}

Expand Down
11 changes: 2 additions & 9 deletions src/Modular.Infrastructure/Logging/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ public static class Extensions
{
private const string ConsoleOutputTemplate = "{Timestamp:HH:mm:ss} [{Level:u3}] {Message}{NewLine}{Exception}";
private const string FileOutputTemplate = "{Timestamp:HH:mm:ss} [{Level:u3}] ({SourceContext}.{Method}) {Message}{NewLine}{Exception}";
private const string AppSectionName = "app";
private const string LoggerSectionName = "logger";

public static IServiceCollection AddLoggingDecorators(this IServiceCollection services)
Expand Down Expand Up @@ -52,21 +51,15 @@ public static IApplicationBuilder UseLogging(this IApplicationBuilder app)
}

public static IHostBuilder UseLogging(this IHostBuilder builder, Action<LoggerConfiguration> configure = null,
string loggerSectionName = LoggerSectionName,
string appSectionName = AppSectionName)
string loggerSectionName = LoggerSectionName)
=> builder.UseSerilog((context, loggerConfiguration) =>
{
if (string.IsNullOrWhiteSpace(loggerSectionName))
{
loggerSectionName = LoggerSectionName;
}

if (string.IsNullOrWhiteSpace(appSectionName))
{
appSectionName = AppSectionName;
}

var appOptions = context.Configuration.GetOptions<AppOptions>(appSectionName);
var appOptions = context.Configuration.GetAppOptions();
var loggerOptions = context.Configuration.GetOptions<LoggerOptions>(loggerSectionName);

MapOptions(loggerOptions, appOptions, loggerConfiguration, context.HostingEnvironment.EnvironmentName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Threading.Tasks;
using Humanizer;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Modular.Abstractions.Contexts;
using Modular.Abstractions.Messaging;
using Modular.Abstractions.Modules;
Expand All @@ -20,19 +21,19 @@ public sealed class InMemoryMessageBroker : IMessageBroker
private readonly IContext _context;
private readonly IOutboxBroker _outboxBroker;
private readonly IMessageContextRegistry _messageContextRegistry;
private readonly MessagingOptions _messagingOptions;
private readonly bool _useAsyncDispatcher;
private readonly ILogger<InMemoryMessageBroker> _logger;

public InMemoryMessageBroker(IModuleClient moduleClient, IAsyncMessageDispatcher asyncMessageDispatcher,
IContext context, IOutboxBroker outboxBroker, IMessageContextRegistry messageContextRegistry,
MessagingOptions messagingOptions,ILogger<InMemoryMessageBroker> logger)
IOptions<MessagingOptions> messagingOptions, ILogger<InMemoryMessageBroker> logger)
{
_moduleClient = moduleClient;
_asyncMessageDispatcher = asyncMessageDispatcher;
_context = context;
_outboxBroker = outboxBroker;
_messageContextRegistry = messageContextRegistry;
_messagingOptions = messagingOptions;
_useAsyncDispatcher = messagingOptions.Value.UseAsyncDispatcher;
_logger = logger;
}

Expand All @@ -41,7 +42,7 @@ public Task PublishAsync(IMessage message, CancellationToken cancellationToken =

public Task PublishAsync(IMessage[] messages, CancellationToken cancellationToken = default)
=> PublishAsync(cancellationToken, messages);

private async Task PublishAsync(CancellationToken cancellationToken, params IMessage[] messages)
{
if (messages is null)
Expand All @@ -60,16 +61,17 @@ private async Task PublishAsync(CancellationToken cancellationToken, params IMes
{
var messageContext = new MessageContext(Guid.NewGuid(), _context);
_messageContextRegistry.Set(message, messageContext);

var module = message.GetModuleName();
var name = message.GetType().Name.Underscore();
var requestId = _context.RequestId;
var traceId = _context.TraceId;
var userId = _context.Identity?.Id;
var messageId = messageContext.MessageId;
var correlationId = messageContext.Context.CorrelationId;

_logger.LogInformation("Publishing a message: {Name} ({Module}) [Request ID: {RequestId}, Message ID: {MessageId}, Correlation ID: {CorrelationId}, Trace ID: '{TraceId}', User ID: '{UserId}]...",

_logger.LogInformation(
"Publishing a message: {Name} ({Module}) [Request ID: {RequestId}, Message ID: {MessageId}, Correlation ID: {CorrelationId}, Trace ID: '{TraceId}', User ID: '{UserId}]...",
name, module, requestId, messageId, correlationId, traceId, userId);
}

Expand All @@ -79,7 +81,7 @@ private async Task PublishAsync(CancellationToken cancellationToken, params IMes
return;
}

var tasks = _messagingOptions.UseAsyncDispatcher
var tasks = _useAsyncDispatcher
? messages.Select(message => _asyncMessageDispatcher.PublishAsync(message, cancellationToken))
: messages.Select(message => _moduleClient.PublishAsync(message, cancellationToken));

Expand Down
10 changes: 6 additions & 4 deletions src/Modular.Infrastructure/Messaging/Extensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Modular.Abstractions.Messaging;
using Modular.Infrastructure.Messaging.Brokers;
using Modular.Infrastructure.Messaging.Contexts;
Expand All @@ -10,16 +11,17 @@ public static class Extensions
{
private const string SectionName = "messaging";

public static IServiceCollection AddMessaging(this IServiceCollection services)
public static IServiceCollection AddMessaging(this IServiceCollection services, IConfiguration configuration)
{
services.AddTransient<IMessageBroker, InMemoryMessageBroker>();
services.AddTransient<IAsyncMessageDispatcher, AsyncMessageDispatcher>();
services.AddSingleton<IMessageChannel, MessageChannel>();
services.AddSingleton<IMessageContextProvider, MessageContextProvider>();
services.AddSingleton<IMessageContextRegistry, MessageContextRegistry>();

var messagingOptions = services.GetOptions<MessagingOptions>(SectionName);
services.AddSingleton(messagingOptions);
var section = configuration.GetSection(SectionName);
var messagingOptions = section.GetOptions<MessagingOptions>();
services.Configure<MessagingOptions>(section);

if (messagingOptions.UseAsyncDispatcher)
{
Expand Down
11 changes: 6 additions & 5 deletions src/Modular.Infrastructure/Messaging/Outbox/EfOutbox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Humanizer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Modular.Abstractions.Messaging;
using Modular.Abstractions.Modules;
using Modular.Abstractions.Time;
Expand All @@ -24,15 +25,15 @@ public sealed class EfOutbox<T> : IOutbox where T : DbContext
private readonly IModuleClient _moduleClient;
private readonly IAsyncMessageDispatcher _asyncMessageDispatcher;
private readonly IJsonSerializer _jsonSerializer;
private readonly MessagingOptions _messagingOptions;
private readonly ILogger<EfOutbox<T>> _logger;
private readonly bool _useAsyncDispatcher;

public bool Enabled { get; }

public EfOutbox(T dbContext, IMessageContextRegistry messageContextRegistry,
IMessageContextProvider messageContextProvider, IClock clock, IModuleClient moduleClient,
IAsyncMessageDispatcher asyncMessageDispatcher, IJsonSerializer jsonSerializer,
MessagingOptions messagingOptions, OutboxOptions outboxOptions, ILogger<EfOutbox<T>> logger)
IOptions<MessagingOptions> messagingOptions, IOptions<OutboxOptions> outboxOptions, ILogger<EfOutbox<T>> logger)
{
_dbContext = dbContext;
_set = dbContext.Set<OutboxMessage>();
Expand All @@ -42,9 +43,9 @@ public EfOutbox(T dbContext, IMessageContextRegistry messageContextRegistry,
_moduleClient = moduleClient;
_asyncMessageDispatcher = asyncMessageDispatcher;
_jsonSerializer = jsonSerializer;
_messagingOptions = messagingOptions;
_useAsyncDispatcher = messagingOptions.Value.UseAsyncDispatcher;
_logger = logger;
Enabled = outboxOptions.Enabled;
Enabled = outboxOptions.Value.Enabled;
}

public async Task SaveAsync(params IMessage[] messages)
Expand Down Expand Up @@ -128,7 +129,7 @@ public async Task PublishUnsentAsync()
_logger.LogInformation("Publishing a message from outbox ('{Module}'): {Name} [Message ID: {MessageId}, Correlation ID: {CorrelationId}]...",
module, name, messageId, correlationId);

if (_messagingOptions.UseAsyncDispatcher)
if (_useAsyncDispatcher)
{
await _asyncMessageDispatcher.PublishAsync(message);
}
Expand Down
Loading

0 comments on commit 05612a2

Please sign in to comment.