Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ public class MediatRServiceConfiguration
/// </summary>
public List<ServiceDescriptor> RequestPostProcessorsToRegister { get; } = new();

/// <summary>
/// Automatically register processors during assembly scanning
/// </summary>
public bool AutoRegisterRequestProcessors { get; set; }

/// <summary>
/// Register various handlers from assembly containing given type
/// </summary>
Expand Down
14 changes: 13 additions & 1 deletion src/MediatR/Registration/ServiceRegistrar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,25 @@ public static void AddMediatRClasses(IServiceCollection services, MediatRService
ConnectImplementationsToTypesClosing(typeof(IRequestExceptionHandler<,,>), services, assembliesToScan, true, configuration);
ConnectImplementationsToTypesClosing(typeof(IRequestExceptionAction<,>), services, assembliesToScan, true, configuration);

var multiOpenInterfaces = new[]
if (configuration.AutoRegisterRequestProcessors)
{
ConnectImplementationsToTypesClosing(typeof(IRequestPreProcessor<>), services, assembliesToScan, false, configuration);
ConnectImplementationsToTypesClosing(typeof(IRequestPostProcessor<,>), services, assembliesToScan, false, configuration);
}

var multiOpenInterfaces = new List<Type>
{
typeof(INotificationHandler<>),
typeof(IRequestExceptionHandler<,,>),
typeof(IRequestExceptionAction<,>)
};

if (configuration.AutoRegisterRequestProcessors)
{
multiOpenInterfaces.Add(typeof(IRequestPreProcessor<>));
multiOpenInterfaces.Add(typeof(IRequestPostProcessor<,>));
}

foreach (var multiOpenInterface in multiOpenInterfaces)
{
var arity = multiOpenInterface.GetGenericArguments().Length;
Expand Down
23 changes: 23 additions & 0 deletions test/MediatR.Tests/MicrosoftExtensionsDI/PipelineTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,29 @@ public void Should_handle_open_behaviors_registration_from_a_single_type()
});
}

[Fact]
public void Should_auto_register_processors_when_configured()
{
var cfg = new MediatRServiceConfiguration
{
AutoRegisterRequestProcessors = true
};

var output = new Logger();
IServiceCollection services = new ServiceCollection();
services.AddSingleton(output);

cfg.RegisterServicesFromAssemblyContaining<Ping>();

services.AddMediatR(cfg);

var provider = services.BuildServiceProvider();

provider.GetServices(typeof(IRequestPreProcessor<Ping>)).Count().ShouldBeGreaterThan(0);
provider.GetServices(typeof(IRequestPostProcessor<Ping, Pong>)).Count().ShouldBeGreaterThan(0);
}


public sealed record FooRequest : IRequest;

public interface IBlogger<T>
Expand Down