简体   繁体   English

使用简单注入器在静态类中进行属性注入

[英]Property injection in static class with Simple Injector

I have used dependency injection from simple injector. 我使用了来自简单注入器的依赖注入。 Now I am trying to implement property injection but the help document is not helping much. 现在,我正在尝试实现属性注入,但是帮助文档帮助并不大。

Can anyone explain with simple example how property injection work? 谁能用简单的例子解释属性注入的工作原理?

I want to use it in one Utility class of Web Project, not in controller. 我想在Web Project的一个Utility类中使用它,而不是在控制器中使用它。 And that class method is static. 该类方法是静态的。

The documentation does not explain how to inject a static property because this is not supported in Simple Injector. 该文档未说明如何注入静态属性,因为Simple Injector不支持此属性。

Static properties are typically a bad idea, because they hinder testability, cause Temporal Coupling , and can cause Captive Dependencies . 静态属性通常不是一个好主意,因为它们会阻碍可测试性,导致时间耦合 ,并可能导致依赖关系

If a static property is required, you will have to inject the dependency yourself. 如果需要静态属性,则必须自己注入依赖项。 You can do that in the Composition Root , right after you made all the registrations to the Container. 在对容器进行所有注册之后,就可以在“ 合成根目录”中执行此操作。

Example: 例:

var container = new Container();

// Make registrations to container here:

container.Verify();

Utility.MyStaticProperty = container.GetInstance<IDependency>();

Under normal conditions, Simple Injector will detect these types of Lifestyle Mismatches , but it will not be able to do so when you inject this property yourself. 在正常情况下,Simple Injector将检测到这些类型的生活方式不匹配 ,但是当您自己注入此属性时,它将无法检测到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM