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

Possibility to make remove certain handlers from the ServiceCollection #39

Closed
Tornhoof opened this issue May 31, 2022 · 0 comments · Fixed by #42
Closed

Possibility to make remove certain handlers from the ServiceCollection #39

Tornhoof opened this issue May 31, 2022 · 0 comments · Fixed by #42

Comments

@Tornhoof
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant