1
votes

I'd like to inject a dependency into an NServiceBus Message Mutator... since the lifetime of the Mutators is controlled by NServiceBus (and NSB wants a paramaterless constructor), constructor injection won't work...

any ideas?

UPDATE: Here is the code:

public class AddTransactionInformationToOutgoingHeaders : 
                            IMutateOutgoingTransportMessages, 
                            INeedInitialization
{
    private readonly IProvideTransactionInformation transactionInformationProvider;

    public void Init()
    {
        Configure.Instance.Configurer.ConfigureComponent<AddTransactionInformationToOutgoingHeaders>(DependencyLifecycle.InstancePerCall);
    }

    public AddTransactionInformationToOutgoingHeaders()
    {
    }

    public AddTransactionInformationToOutgoingHeaders(IProvideTransactionInformation transactionInformationProvider)
    {
        this.transactionInformationProvider = transactionInformationProvider;
    }

    public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
    {
        ...
    }
}

}

If I take away the empty ctor, I get this error message thrown from my ConfigureBus() call in Global.asax: "No parameterless constructor defined for this object."

2

2 Answers

2
votes

To get around this, I just kept one empty constructor for NServiceBus and then created a overloaded constructor that took my dependency that is managed by Unity.

It works.

Didn't know that mutators could work like that. It was my first time trying to inject a dependency into one.

UPDATE:

I got around this by using property injection on the mutator instead:

public class AddTransactionInformationToOutgoingHeaders : IMutateOutgoingTransportMessages, INeedInitialization
{
    public IProvideTransactionInformation TransactionInformationProvider { get; set; }

    public void Init()
    {
        Configure.Instance.Configurer.ConfigureComponent<AddTransactionInformationToOutgoingHeaders>(DependencyLifecycle.InstancePerCall);
    }

    public void MutateOutgoing(object[] messages, TransportMessage transportMessage)
    {
        ...
    }
}

Worked perfectly.

1
votes

Pretty sure both constructor and property injection should work. What is the exception?