Property injection

Component: NServiceBus
NuGet Package NServiceBus (7.2-pre)
This page targets a pre-release version and is subject to change prior to the final release.

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:

7.x - 7.1 NServiceBus
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:

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

Last modified