[英]Exchanging data between classes - DI, IoC
My setup is:我的设置是:
class ModelA { ... }
interface IModelARetriever { IEnumerable<ModelA> GetObjects(); }
class ModelB { ... }
class DomainObject { List<ModelB> ModelBList; }
DomainObject.ModelBList
could be appended using manipulated data from lists of ModelA
objects, but not neccessarily. DomainObject.ModelBList
可以使用来自ModelA
对象列表的操作数据附加,但不是必须的。 Where should I put the logic for this?我应该把这个逻辑放在哪里?
Should I create a method in DomainObject
that takes a IEnumerable<ModelA>
?我应该在
DomainObject
中创建一个采用IEnumerable<ModelA>
的方法吗? That would mean changing the DomainObject
for every possible source of data that can create objects of ModelB.这将意味着为可以创建 ModelB 对象的每个可能的数据源更改
DomainObject
。
Should I create a separate interface ModelBFactory
and extend that?我应该创建一个单独的
interface ModelBFactory
并扩展它吗? This sounds best, but just want an expert opinion.这听起来最好,但只是想要专家意见。
If I've read the question correctly, ModelA
objects can be converted into ModelB
objects.如果我正确阅读了问题,可以将
ModelA
对象转换为ModelB
对象。 I'd say that calls for a ToModelB()
method on ModelA
.我会说这需要 ModelA 上的
ModelA
ToModelB()
方法。 If the conversion is straightforward (say, just copying a subset of ModelA
's property values), I'd implement it in ToModelB()
directly;如果转换很简单(例如,只是复制
ModelA
的属性值的子集),我会直接在ToModelB()
中实现它; if it's more complex (say, conditional copying of some property values, combination of values, arithmetic, etc) I'd have a ModelAConverter
class which did the job.如果它更复杂(例如,某些属性值的条件复制、值的组合、算术等),我将有一个
ModelAConverter
class 来完成这项工作。
I'd then add the AddModelAObjects()
method you mentioned to DomainObject
.然后,我会将您提到的
AddModelAObjects()
方法添加到DomainObject
。 You then have two choices of how you convert the ModelA
s into ModelB
s - you either have the ModelAConverter
injected into DomainObject
's constructor and do the conversion in AddModelAObjects()
, or into ModelA
's constructor and do the conversion in ToModelB()
.然后,您有两种选择如何将
ModelA
转换为ModelB
- 您可以将ModelAConverter
注入DomainObject
的构造函数并在AddModelAObjects()
中进行转换,或者注入ModelA
的构造函数并在ToModelB()
中进行转换. I'd probably go with the latter, but it depends on what else the objects have to do.我可能会 go 与后者,但这取决于对象还需要做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.