EventProcessorHost Inject Dependencies

Processing with Azure EventHubs can be significantly simplified if using EventProcessorHost. EventProcessorHost is using Azure Storage account to track last read locations (pointers) in event hub partitions.

enter image description here

In order to start a host, eventHubName, eventHubConnectionString, and storageConnectionString need to be passed in (eventProcessorHostName could be a GUID or anything else).

var eventProcessorHost = new EventProcessorHost(eventProcessorHostName, eventHubName, EventHubConsumerGroup.DefaultGroupName, eventHubConnectionString, storageConnectionString);

Once a host is created, a processor needs to be specified. A processor is a class implementing IEventProcessor contact which will allow to open and close processor, and process events data.

eventProcessorHost.RegisterEventProcessorAsync<SimpleEventProcessor>();

While this is working great, there's no simple way to inject dependencies into the processor you define using registration demonstrated above. Gladly, there's a factory registration that allows registering IEventProcessorFactory implementation.

eventProcessorHost.RegisterEventProcessorFactoryAsync(new EventProcessorFactory(dependency))

Where EventProcessorFactory is defined as follow:

class EventProcessorFactory : IEventProcessorFactory
{
    private readonly IDependency dependency;

    public EventProcessorFactory(IDependency dependency)
    {
        this.dependency= dependency;
    }

    public IEventProcessor CreateEventProcessor(PartitionContext context)
    {
        return new SimpleEventProcessor(dependency);
    }
}

And now we can define our SimpleEventProcessor processor with any dependencies that we want.

Happy processing!

2 Comments

  • Hi,

    I am trying to do this using structure map but not having much luck.

    I am using a worker role in azure and have tried using the EventProcessorFactory as a way of passing in dependencies.

    In your example, is dependency a class object that you pass into EventProcessorFactory from the calling method?

    I've seen other implementation of this concept which passes in a reference to the IOC container itself

    Cheers
    Macca

  • @Macca,

    In my case I had the following:
    eventProcessorHost.RegisterEventProcessorFactoryAsync(new EventProcessorFactory(dependency))

    If I'd use some sort of container, I'd assume that dependency would be resolved from that one using something like:
    dependency = container.Resolve<IDependency>();

    and then passed into EventProcessorFactory constructor.

Comments have been disabled for this content.