Property injection

Component: NServiceBus
NuGet Package NServiceBus (7.x)

NServiceBus will automatically enable property injection for known types across the supported dependency injection libraries. Use the Func overload of .ConfigureComponent to get full control over the injected properties if needed.

A common use case is to set primitive properties on message handlers. Given the below handler:

public class EmailHandler :
    IHandleMessages<EmailMessage>
{
    public string SmtpAddress { get; set; }
    public int SmtpPort { get; set; }

    public Task Handle(EmailMessage message, IMessageHandlerContext context)
    {
        using (var client = new SmtpClient(SmtpAddress, SmtpPort))
        {
            // use client
        }
        return Task.CompletedTask;
    }
}

Setting the properties is done as follows:

endpointConfiguration.RegisterComponents(
    registration: components =>
    {
        components.ConfigureComponent(
            builder =>
            {
                return new EmailHandler
                {
                    SmtpPort = 25,
                    SmtpAddress = "10.0.1.233"
                };
            },
            dependencyLifecycle: DependencyLifecycle.InstancePerUnitOfWork);
    });

Last modified