[英]How do I inject into base class with Castle Windsor?
I have a series of core services that I want to configure with Castle Windsor, things like Logging, Caching, Email config, etc. Making these services easily configurable by an app.config change would be a great boon (eg even just for development/testing it's great to be able to tell the app to route all the email traffic through some other mechanism than the actual mail server). 我有一系列要使用Castle Windsor配置的核心服务,例如日志记录,缓存,电子邮件配置等。通过app.config更改使这些服务易于配置将是一个巨大的福音(例如,即使是用于开发/测试能够告诉应用程序通过除实际邮件服务器以外的其他机制路由所有电子邮件流量,这非常好。
Two questions: 两个问题:
I hope that makes sense, thank you. 我希望这是有道理的,谢谢。
Regarding your first point, use property injection . 关于第一点,请使用属性注入 。
You have two choices for injecting dependencies; 注入依赖项有两种选择: via the constructor or via properties. 通过构造函数或通过属性。 Since you don't want to pass dependencies down the constructor chain, the only other way is via property injection. 由于您不想将依赖关系传递给构造函数链,因此唯一的其他方法是通过属性注入。 This has the advantage that if a base class need to add/remove/change a dependency, it doesn't affect everything that inherits from it. 这样做的好处是,如果基类需要添加/删除/更改依赖关系,则不会影响继承自该依赖关系的所有内容。
Some folks (myself included) shy away from property injection because it makes dependencies non-obvious and can imply that they are optional. 有些人(包括我自己)回避属性注入,因为这使依赖关系变得不明显,并暗示它们是可选的。 This can make unit testing (you're doing that, right?) difficult because you have to inspect the class to see what dependencies are needed. 这会使单元测试(您正在这样做,对吗?)很困难,因为您必须检查类以查看需要哪些依赖项。 If they were in the constructor, it'd be obvious. 如果它们在构造函数中,那将是显而易见的。
However, if you can make sane null-object implementations of your services so that they are optional, or the unit-testing implications don't phase you, then this is a good route to go down. 但是,如果您可以对服务进行合理的空对象实现 ,以便它们是可选的,或者不对单元测试产生影响,那么这是一个不错的选择。
As to your second question, if you can't control how the class gets created, you can't expect Windsor to supply any of its dependencies. 关于第二个问题,如果您无法控制如何创建类,则不能指望Windsor提供其任何依赖项。 At best, you can resolve the dependencies individually (ie call container.Resolve<IYourDependency>()
) and assign them to the properties of your implementation. 充其量,您可以单独解析依赖项(即,调用container.Resolve<IYourDependency>()
),并将其分配给实现的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.