Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Azure by (45.3k points)

The problem is that the Azure WebJobs SDK supports only public static methods as job entry-points which means there is no way of implementing constructor/property injection.

I am unable to find anything about this topic in official WebJobs SDK documentation/resources. The only solution that I came across is based on service locator (anti) pattern described on this post here.

Is there a good way to use "proper" dependency injection for projects based on the Azure WebJobs SDK?

1 Answer

+1 vote
by (16.8k points)

This is the way to handle scope using the new SDK using the IJobactivator.

public class ScopedMessagingProvider : MessagingProvider

{

    private readonly ServiceBusConfiguration _config;

    private readonly Container _container;

    public ScopedMessagingProvider(ServiceBusConfiguration config, Container container)

        : base(config)

    {

        _config = config;

        _container = container;

    }

    public override MessageProcessor CreateMessageProcessor(string entityPath)

    {

        return new CustomMessageProcessor(_config.MessageOptions, _container);

    }

    private class CustomMessageProcessor : MessageProcessor

    {

        private readonly Container _container;

        public CustomMessageProcessor(OnMessageOptions messageOptions, Container container)

            : base(messageOptions)

        {

            _container = container;

        }

        public override Task<bool> BeginProcessingMessageAsync(BrokeredMessage message, CancellationToken cancellationToken)

        {

            _container.BeginExecutionContextScope();

            return base.BeginProcessingMessageAsync(message, cancellationToken);

        }

        public override Task CompleteProcessingMessageAsync(BrokeredMessage message, FunctionResult result, CancellationToken cancellationToken)

        {

            var scope = _container.GetCurrentExecutionContextScope();

            if (scope != null)

            {

                scope.Dispose();

            }

            return base.CompleteProcessingMessageAsync(message, result, cancellationToken);

        }

    }

}

You can use your own custom MessagingProvider in the JobHostConfiguration like

var serviceBusConfig = new ServiceBusConfiguration

    ConnectionString = config.ServiceBusConnectionString

};

serviceBusConfig.MessagingProvider = new ScopedMessagingProvider(serviceBusConfig, container);

jobHostConfig.UseServiceBus(serviceBusConfig);

Browse Categories

...