3

I am using Umbraco 7.1.1 with an MVC project, and I've configured it to use dependency injection (Castle.Windsor in my case). I'm also using NServiceBus to send messages etc and it's working pretty well.

I am now attempting to hook into the ContentService Published event - to try and publish an NServiceBus event to alert other services that the content has changed. What I would like to do is something like this:

public class ContentPublishedEventHandler : ApplicationEventHandler
{
    public IBus Bus { get; set; }

    public ContentPublishedEventHandler()
    {
        ContentService.Published += ContentServiceOnPublished;
    }

    private void ContentServiceOnPublished(IPublishingStrategy sender, PublishEventArgs<IContent> publishEventArgs)
    {
        Bus.Publish<ContentUpdatedEvent>(e =>
        {
            e.UpdatedNodeIds = publishEventArgs.PublishedEntities.Select(c => c.Id);
        });
    }
}

But in this case, Bus is null as my dependency injection framework is either not configured properly, or (as I suspect), never invoked.

I can get it to work if I rely on a static reference to the bus, but I'd prefer to avoid that if I can. Is what I'm trying to do possible? Ie use dependency injection with these Umbraco events? If so, what configuration do I need to tell Umbraco to use Castle.Windsor to create my event handler?

thecodefish
  • 388
  • 2
  • 13

1 Answers1

0

if you are still looking for the answer it would be better to inject dependency in ContentPublishedEventHandler constructor, so the code would be looked like this:

public class ContentPublishedEventHandler : ApplicationEventHandler
{
    public IBus Bus { get; set; }
    
    public ContentPublishedEventHandler(IBus bus)
    {
        Bus = bus;
    }

    protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        ContentService.Published += ContentServiceOnPublished;

        base.ApplicationStarting(umbracoApplication, applicationContext);
    }
        
    
    private void ContentServiceOnPublished(IPublishingStrategy sender, PublishEventArgs<IContent> publishEventArgs)
    {
        Bus.Publish<ContentUpdatedEvent>(e =>
        {
            e.UpdatedNodeIds = publishEventArgs.PublishedEntities.Select(c => c.Id);
        });
    }
}

If you are lookin for more info about using Dependency Injection with Umbraco 7 please refer to https://web.archive.org/web/20160325201135/http://www.wearesicc.com/getting-started-with-umbraco-7-and-structuremap-v3/

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Pawel Bres
  • 24
  • 2