微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

依赖注入 – NServiceBus依赖注入

我一直遇到这个问题.

AndreasÖhlund在here回答了一个问题,但是我一直无法使用他给出的建议来解决这个问题.

这是我的设置:

public abstract class CommandHandler<T> : IHandleMessages<T>,IDomainReadRepository where T : Command
{
    public IDomainRepository DomainRepository { get; set; }

    protected abstract void OnProcess(T command);

    public TAggregate GetById<TAggregate>(Guid id) where TAggregate : IEventProvider,new()
    {
        return DomainRepository.GetById<TAggregate>(id);
    }

    public void Handle(T message)
    {
        OnProcess(message);
        // Domain repository will save.
    }
}

这个想法是特定的命令处理程序覆盖OnProcess方法并做他们的事情,然后DomainRepository将保存所有内容.

以下是我注册组件的方法

public class EndpointConfig : IConfigureThisEndpoint,AsA_Server,IWantCustomInitialization
{
    public void Init()
    {
        Configure.With().DefiningCommandsAs(c => c.Namespace != null && c.Namespace.EndsWith("Commands"));
        Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<DomainRepository>(DependencyLifecycle.InstancePerCall);
        Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<EventStore.sql.EventStore>(DependencyLifecycle.InstancePerCall);
        Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<MongoDbObjectSecurityDescriptorRepository>(DependencyLifecycle.InstancePerCall);
        Configure.Instance.DefaultBuilder().Configurer.ConfigureComponent<LocalTenantConfig>(DependencyLifecycle.InstancePerCall);
    }
}

这些是DomainRepository使用的链中的所有对象;但是,当我收到命令时,DomainRepository为null.如果我注释掉注册DomainRepository所需对象的行,我实际上会收到一条错误,说它无法创建它(Autofac DependencyResolutionException).

应该注意的是,所有其他对象都使用构造函数注入(它们来自先前存在的项目).我尝试将它们更改为使用公共属性注入,但它没有任何区别.

如果有人能指出我在这里做错了什么,我将不胜感激!

解决方法

将init方法中的代码移动到实现INeedInitialization的其他类中.在那里,使用Configure.Instance而不是Configure.With(),而不是Configure.Instance.DefaultBuilder().

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐