Skip to content

Commit

Permalink
Add test helper that registers a type with all its interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
kzu committed Nov 18, 2022
1 parent 8b8cc75 commit 00dba35
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Merq.Core/MessageBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ static Type GetCommandType(IExecutable command)
var generic = descriptor.ServiceType.GetGenericTypeDefinition();
// Consider both void and non-void handlers
if (generic != typeof(IExecutableCommandHandler<>) &&
generic != typeof(IExecutableCommandHandler<,>) &&
generic != typeof(IExecutableCommandHandler<,>) &&
generic != typeof(ICommandHandler<>) &&
generic != typeof(ICommandHandler<,>) &&
generic != typeof(IAsyncCommandHandler<>) &&
Expand Down
30 changes: 30 additions & 0 deletions src/Merq.Tests/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using Microsoft.Extensions.DependencyInjection;

namespace Merq;

public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAll<TImplementation>(this IServiceCollection services)
where TImplementation : class, new()
{
AddAll(services, _ => new TImplementation());
return services;
}

public static IServiceCollection AddAll<TImplementation>(
this IServiceCollection services,
Func<IServiceProvider, TImplementation> implementationFactory)
where TImplementation : class
{
// Simulates what the DependencyInjection.Attribute does, by registering
// the implementation with all the interfaces it implements.

services.AddSingleton(implementationFactory);

foreach (var interfaceType in typeof(TImplementation).GetInterfaces())
services.AddSingleton(interfaceType, s => s.GetRequiredService(typeof(TImplementation)));

return services;
}
}

0 comments on commit 00dba35

Please sign in to comment.