[英]How to write own logic to initialize a property with Unity?
Let's suppose you have Class A and Class B. Both these classes have a private variable:假设您有 Class A 和 Class B。这两个类都有一个私有变量:
private Store _store {get;set}
class Class A
{
private Store _store {get;set}
constructor()
{
init(param1,param2,..);
}
init(param1,param2,..)
{
//logic to initialize _store
}
}
class Class B
{
private Store _store {get;set}
constructor()
{
init(param1,param2,..);
}
init(param1,param2,..)
{
//logic to initialize _store
}
}
Problem: duplicate init()
code问题:重复
init()
代码
My Solutions:我的解决方案:
StoreFactory
class with a Init
method that will return a Store instance.Init
方法创建StoreFactory
class。 Is there a third way to achieve this?有没有第三种方法可以实现这一目标? Perhaps with dependency injection container Unity?
也许使用依赖注入容器 Unity? I would also be interested in knowing any other way of achieving this.
我也有兴趣知道实现这一目标的任何其他方式。 With or without unity.
有或没有统一。
I would avoid the inheritance .我会避免使用inheritance 。 Composing is likely to be easier for maintenance in the long run compared to the inheritance , for this reason i will prefer the factory approach or injecting some service into the classes.
从长远来看,与inheritance相比,编写可能更容易维护,因此我更喜欢工厂方法或向类中注入一些服务。
Another approach will be to have the Init
method as part of the Store
class definition.另一种方法是将
Init
方法作为Store
class 定义的一部分。 And inject the Store
class into the constructors of Class A
and B
( Unity will take care of the wiring).并将
Store
class 注入Class A
和B
的构造函数中( Unity将负责接线)。
Then you can call the Init
method of the Store
instead of relying on injecting the factory in each class where the store will be used.然后,您可以调用
Store
的Init
方法,而不是依赖于在将使用 store 的每个 class 中注入工厂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.