Property injection using the default NSB DI in .net core

I use Nservicebus default container (autofac) in my endpoint. The registration of the service is through NSB API
endpointConfiguration.RegisterComponents(c => c.ConfigureComponent<ServiceAWorker>(DependencyLifecycle.InstancePerCall));

Moving to .net core, It seems like the property injection doesn’t work in the endpoint by using the NSB default container.
Is there a way to make it work without changing the code above to register a component?

What version of NServiceBus are you using?

Are you by any chance using our extensions for MS DependencyInjection?

I ask since the abstractions from Microsoft doesn’t support property injection and you would have to either use funcs to set the properties your self or make sure to use a container that supports property injection like Autofac.

Thanks for the quick response. NServiceBus (7.3.0). Yeah. I was aware of property injection limitations of MS DI. We were trying to use Autofac but using the NSB api to register.
I created a sample PropertyInjectionSample

How can I make the property injection work without changing the dependency registration? trying to port existing application and want to minimize scope.

I think it should work if you call PropertiesAutowired when registering your components in AutoFac

https://autofaccn.readthedocs.io/en/latest/register/prop-method-injection.html#property-and-method-injection

Have you tried that?

But the handler where I need the dependency is registered by NSB,right? Is Nservicebus still using Autofac as the default container?

This is where I need the property injection.

 public class TestPropertyInjectionHandler : IHandleMessages<TestPropertyInjection>
    {
        public ILogger<TestPropertyInjectionHandler> Logger { get; set; }

        public IDoSomeServiceAWork ServiceWorker { get; set; }
        public Task Handle(TestPropertyInjection message, IMessageHandlerContext context)
        {
            Logger.LogInformation(ServiceWorker.DoSomething());

And here is the registration

public class Configure : INeedInitialization
    {
        public void Customize(EndpointConfiguration endpointConfiguration)
        {
            endpointConfiguration.RegisterComponents(c => c.ConfigureComponent<SomeServiceAWork>(DependencyLifecycle.InstancePerCall));
        }
    }

But the handler where I need the dependency is registered by NSB,right?

Correct, so for this to work you have to re-register them in AutoFac with the mentioned PropertiesAutowired setting.

Is Nservicebus still using Autofac as the default container?

No, since v6 LightInject is embedded and used as the “internal” container.

ok. That explains it. Thanks.

Just wondering whether there is a way to make it work without re-registering handlers?

Not that I’m aware of but there might be some Autofac trickery that would enable you to turn this on by default for all registrations so it might be worth asking them for advice?

1 Like