静态属性注入配置最佳实践
我在多个类中使用了辅助组件。这是典型的场景:
public class HelperComponent
{
public void HelperMethod()
{
// do something
}
}
public class MyClass
{
private static HelperComponent Helper{ get; set;}
public void Method1()
{
Helper.HelperMethod();
}
}
用法: new MyClass().Method1();
我想知道对于此配置建议的 spring.net 配置/解决方案是什么? 最初我使用这一行来获取辅助组件:
ContextRegistry.GetContext().GetObject("HelperComponentName")
然后我读到这不是更好的解决方案,我应该使用注入以避免对 spring 的依赖并具有透明的组件使用。
我的问题是:如何使用 spring 配置来实现这一点?
我可以将静态属性注入到类中吗?或者我应该创建 Helper 实例属性吗? 如果我将Helper转换为实例属性,是否需要在spring配置中定义MyClass并使用CreateObject实例化MyClass?
如果是,这对我来说不是令人满意的解决方案,因为我想实例化上面写的 MyClass 。
任何帮助表示赞赏。
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();
I would like to know what is advised spring.net configuration/solution for this configuration?
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.
My question is: how can I achieve this using spring configuration?
Can I inject static property into class? Or should I make Helper instance property?
If I convert Helper to instance property, do I need to define MyClass in spring configuration and use CreateObject to instantiate MyClass?
If yes, it isn't satisfiable solution for me beacuse I would like to instantiate MyClass as written above.
Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对 spring 不太熟悉,但是在使用 IOC 容器时,您通常会注册应用程序的所有依赖项(及其生命周期),然后解析对象图顶部的“入口点”对象。
这使您可以利用 IOC 容器的功能,例如构造函数和属性注入。
一旦完成这样的设置,您就可以通过 IOC 容器配置来管理各个对象的生命周期。
在本例中,在 IOC 容器配置中将
HelperComponent
注册为单例后,我将在MyClass
的构造函数中注入HelperComponent
。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.
This allows you to take advantage of features of the IOC container like constructor and property injection.
Once you are set up like this, you can manage the individual objects life cycles through the IOC containers configuration.
In this case, I would inject
HelperComponent
in the constructor ofMyClass
after registering theHelperComponent
as a singleton in the IOC container configuration.