简体   繁体   English

静态属性注入配置最佳实践

[英]Static property injection configuration best practice

I have helper component used in multiple classes. 我在多个类中使用了帮助程序组件。 This is typical scenario: 这是典型的场景:

public class HelperComponent 
{
    public void HelperMethod() 
    {
        // do something
    }
}

public class MyClass 
{
    private static HelperComponent Helper{ get; set;}

    public void Method1() 
    {
        Helper.HelperMethod();
    }
}

usage: new MyClass().Method1(); 用法: new MyClass().Method1();

I would like to know what is advised spring.net configuration/solution for this configuration? 我想知道建议使用spring.net配置/此配置的解决方案吗? Initially I used this line to fetch helper component: 最初,我使用此行来获取帮助程序组件:

ContextRegistry.GetContext().GetObject("HelperComponentName")

Then I read that this isn't preferable solution and that I should use injection in order to avoid dependency to spring and have transparent component usage. 然后,我读到这不是最佳解决方案,并且应该使用注入以避免对spring的依赖并透明使用组件。

My question is: how can I achieve this using spring configuration? 我的问题是:如何使用spring配置实现这一目标?

Can I inject static property into class? 我可以将静态属性注入类吗? Or should I make Helper instance property? 还是应该设置Helper实例属性? If I convert Helper to instance property, do I need to define MyClass in spring configuration and use CreateObject to instantiate MyClass? 如果将Helper转换为实例属性,是否需要在弹簧配置中定义MyClass并使用CreateObject实例化MyClass?
If yes, it isn't satisfiable solution for me beacuse I would like to instantiate MyClass as written above. 如果是,对我来说这不是令人满意的解决方案,因为我想实例化上面编写的MyClass。

Any help appreciated. 任何帮助表示赞赏。

I'm not that familiar with spring, but when using an IOC container, you usually register all of your application's dependencies (and their life cycles) and then resolve the 'entry-point' object at the top of the object graph. 我对spring不太熟悉,但是当使用IOC容器时,通常会注册所有应用程序的依赖项(及其生命周期),然后在对象图的顶部解析“入口点”对象。

This allows you to take advantage of features of the IOC container like constructor and property injection. 这使您可以利用IOC容器的功能,例如构造函数和属性注入。

Once you are set up like this, you can manage the individual objects life cycles through the IOC containers configuration. 像这样设置后,就可以通过IOC容器配置管理各个对象的生命周期。

In this case, I would inject HelperComponent in the constructor of MyClass after registering the HelperComponent as a singleton in the IOC container configuration. 在这种情况下,我需要在IOC容器配置中将HelperComponent注册为单例之后,将HelperComponent注入MyClass的构造函数中。

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

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