rebus-org / Rebus.ServiceProvider

:bus: Microsoft Extensions Dependency Injection container adapter for Rebus
https://mookid.dk/category/rebus
Other
65 stars 32 forks source link

change activator injection to allow outside dependency replacement #41

Closed marmagni closed 3 years ago

marmagni commented 3 years ago

Rebus is MIT-licensed. The code submitted in this pull request needs to carry the MIT license too. By leaving this text in, I hereby acknowledge that the code submitted in the pull request has the MIT license and can be merged with the Rebus codebase.

mookid8000 commented 3 years ago

Hi @marmagni , your PR looks fine 🙂

What problem does it solve?

marmagni commented 3 years ago

Hi @mookid8000,

Tks feedback, this change can help outside injection replacement to allow custom implementation of IHandlerActivator. This would be useful when we need to change some injection values by transaction, like below example:

  1. Configuration:
    
    //Configure Rebus
    services.AddRebus((configure, provider) => ...);

//Replace default handle activator to my custom services.AddSingleton<IHandlerActivator, MyCustomHandlerActivator>();


2. Useful Example:

public class MyCustomHandlerActivator : DependencyInjectionHandlerActivator, IHandlerActivator { //ctor...

public new Task<IEnumerable<IHandleMessages<TMessage>>> GetHandlers<TMessage>(TMessage message, ITransactionContext transactionContext)
{
    //Re-use base implementation
    var handlers = base.GetHandlers(message, transactionContext);

    //Is this better way to get context?
    var stepContext = transactionContext.GetOrNull<IncomingStepContext>(StepContext.StepContextKey);
    var provider = stepContext.Load<IServiceScope>().ServiceProvider;

    //This will change the cross cutting user accesor by transaction
    var userAccessor = provider.GetService<IUserAccessor>();

    var msgHeaders = MessageContext.Current.Headers;
    msgHeaders.TryGetValue("user_id", out userId);

    userAccessor.User = new User(userId);

    return handlers;
}

}

skwasjer commented 3 years ago

@mookid8000 this would solve a (different) use case we have too, when can we have this? ;)

mookid8000 commented 3 years ago

Thanks for your PR! 🙂 I've released it as Rebus.ServiceProvider 6.1.0

Sorry for taking so long to process this 😐

mookid8000 commented 3 years ago

FYI I've already released Rebus.ServiceProvider 6.2.0 - it has additional targets so it can work with .NET 5