Skip to content

Possibility to make remove certain handlers from the ServiceCollection #39

@Tornhoof

Description

@Tornhoof

At the moment the DI registration for INotificationHandlers registers them all via SP.GetRequiredService.
I have the use case that in some cases (tests or certain features are disabled) I'd like to remove certain NotificationHandlers from the global list, as they might have unintended side effects for tests or a simply disabled.
Let's assume I have a notification MyNotification and an implementation handler MyNotificationHandler, which I want to remove.

Conceptionally the code looks like this for a ServiceDescription registration:

 var sd = new ServiceDescriptor(typeof(INotificationHandler<MyNotification>), p => p.GetRequiredService<MyNotificationHandler>(), ServiceLifetime.Singleton);

due to the fact how the registration works, the functor is actually Func<IServiceProvider, object> making it impossible to obtain the real implementation type via reflection without reverting to tricks like IL inspection.

I propose to change the registration to something like:

 var sd = new ServiceDescriptor(typeof(INotificationHandler<MyNotification>), GetRequiredService<MyNotificationHandler>(), ServiceLifetime.Singleton);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Func<IServiceProvider, object> GetRequiredService<T>() where T : notnull
{
    return provider => provider.GetRequiredService<T>();
}

The above code results in a delegate target which looks like this: <>c__2<MyNotificationHandler> and this allows us to identify the correct handler to remove.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions