dependency-injection - 是否可以将依赖注入(inject)与 Umbraco 7 ContentService 事件处理程序一起使用?

标签 dependency-injection umbraco7

我将 Umbraco 7.1.1 与 MVC 项目一起使用,并且我已将其配置为使用依赖项注入(inject)(在我的例子中是 CaSTLe.Windsor)。我还使用 NServiceBus 发送消息等,它运行良好。

我现在正尝试连接到 ContentService Published 事件 - 尝试发布 NServiceBus 事件以提醒其他服务内容已更改。我想做的是这样的:

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);
        });
    }
}

但在这种情况下,Bus 为空,因为我的依赖注入(inject)框架配置不正确,或者(正如我怀疑的那样)从未被调用。

如果我依赖对总线的静态引用,我可以让它工作,但如果可以的话,我宁愿避免这种情况。我正在尝试做的事情可能吗?即对这些 Umbraco 事件使用依赖注入(inject)?如果是这样,我需要什么配置来告诉 Umbraco 使用 CaSTLe.Windsor 来创建我的事件处理程序?

最佳答案

如果您仍在寻找答案,最好在 ContentPublishedEventHandler 构造函数中注入(inject)依赖项,这样代码将如下所示:

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);
        });
    }
}

如果您正在寻找有关在 Umbraco 7 中使用依赖注入(inject)的更多信息,请参阅 https://web.archive.org/web/20160325201135/http://www.wearesicc.com/getting-started-with-umbraco-7-and-structuremap-v3/

关于dependency-injection - 是否可以将依赖注入(inject)与 Umbraco 7 ContentService 事件处理程序一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24048127/

相关文章:

asp.net-mvc-3 - 如何在.NET MVC3中注入(inject)用于验证的依赖项?

umbraco - 如何创建使用外部数据源的 umbraco 小部件?

.net - Umbraco 7 自定义成员和角色提供者

java - 根据参数重用Guice中的Provide

java - 构造函数注入(inject)与字段注入(inject)

c# - 如何从startup.cs(ASP.NET Core)构造函数中创建具有依赖项的类实例

java - Jersey 2.22 : Where should I define the location of REST resources?

c# - Umbraco从7.2.8升级到7.3.0破坏了网站

c# - 为什么我不能在我自己的类中访问 UmbracoHelper

javascript - Umbraco 属性编辑器不工作