• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

的喷油器在基类注入属性

用户头像
it1352
帮助1

问题说明

有关几个星期我一直在使用href=\"https://simpleinjector.org\" rel=\"nofollow\">简单的注射器依赖注入容器,大获成功的

For several weeks I've been using the Simple Injector dependency injection container, with great success. I love the easy by which I can configure it. But now I have a design that I don't know how to configure. I have a base class where many types from derive, and I want to inject a dependency into a property of the base class, but without having to configure that for every derived class. I tried to do this with attributes, but Simple Injector does not support attributes. Here is a trimmed down version of my design.

public interface Handler<TMessage> where TMessage : Message
{
    void Handle(TMessage message);
}

public abstract class BaseHandler
{
    // This property I want to inject
    public HandlerContext Context { get; set; }
}

// Derived type
public class NotifyCustomerHandler : BaseHandler,
    Handler<NotifyCustomerMessage>
{
    public NotifyCustomerHandler(SomeDependency dependency)
    {
    }

    public void Handle(NotifyCustomerMessage message)
    {
    }
}

我的配置现在看起来是这样的:

My configuration now looks like this:

container.Register<HandlerContext, AspHandlerContext>();
container.Register<Handler<NotifyCustomerMessage>, NotifyCustomerHandler>();
// many other Handler<T> lines here



我怎么能注入在BaseHandler财产?

How can I inject the property in the BaseHandler?

在您的帮助谢谢

正确答案

#1

简单喷油器的物业注入文档提供了有关这是一个非常明确的解释。基本的选项是:

The Simple Injector documentation on property injection gives a very clear explanation about this. The basic options are:

    • 使用注册一个初始化委托 RegisterInitializer
    • 覆盖简单的喷油器的 PropertySelectionBehavior
  • Register an initialization delegate using RegisterInitializer.
  • Override Simple Injector's PropertySelectionBehavior.

由于文件解释说,使用 RegisterInitializer 不建议对房地产的依赖注射;仅在配置值。

As the documentation explains, the use of RegisterInitializer is not advised for property injection on dependencies; only on configuration values.

这让你有压倒一切的简单喷油器的 PropertySelectionBehavior ,但其本身不具有一个基类气味像一个坚实的冲突。请看看下面的文章。它描述了为什么有一个基类可能是一个坏主意,文章提出了一个解决方案。

This leaves you with overriding Simple Injector's PropertySelectionBehavior, but having a base class by itself smells like a SOLID violation. Please take a look at the following article. It describes why having a base class might be a bad idea and the article presents a solution for this.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkehe
系列文章
更多 icon
同类精品
更多 icon
继续加载