如何处理业务层和数据访问层之间的双向依赖关系?
我有一个具有三层(表示层、业务逻辑层和数据访问层)的应用程序。在数据访问层中,我有一个名为 Unit
的对象,在业务层中我有另一个名为 Unit
的对象。
当业务层的Unit
对象上调用Insert()
时,就会调用数据中对应对象的Insert()
方法访问层,并将其自身作为参数传递。我遇到的问题是数据访问层不引用业务层,允许它这样做会导致循环依赖。
我的方法有缺陷吗?如果是这样,什么是解决我的问题的好方法?
I have an application with three layers (Presentation, Business Logic, and Data Access). In the data access layer, I have an object called Unit
, and I have another object called Unit
in the business layer.
When Insert()
is called on the Unit
object in the business layer, it calls the Insert()
method on the corresponding object in the data access layer, and passes itself as the parameter. The problem I have is that the data access layer does not reference the business layer, and allowing it to do so would cause circular dependencies.
Is my approach flawed? If so, what would be a good solution to my problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您声明您的做法需要层之间的双向依赖关系时,您是对的,而这几乎总是一件坏事。这种依赖关系的原因是您的业务逻辑层承担了持久层的一些职责(通过在业务逻辑层中实现
Insert()
)。看起来你在这里混合了两个不兼容的概念。
首先,您声明代码中有三层:表示层、业务层和数据访问层。此声明的问题在于您还声称使用 活动记录 类似模式 (<代码>unit.Insert())。如果您确实具有不同的域(业务)层和持久性(数据访问)层,那么域对象将不知道如何
Insert()
。查看存储库模式。这种模式更适合建立独特的持久层。如果使用此模式,您可以在持久层中定义一个“实体”,并将域层中的
Unit
对象映射到持久层中的Unit
对象。 AutoMapper 应该可以让您免于手动将域模型映射到实体的痛苦。You're right when you state that the way you're doing it would require a bidirectional dependency between layers, and that's almost always a bad thing. The reason for this dependency is that your business logic layer takes on some of the responsibility of the persistence layer (by implementing
Insert()
in the business logic layer).It seems like you're mixing two incompatible concepts here.
First, you state that you have three layers in your code: presentation, business, and data access. The problem with this statement is that you also claim to be using an active record like pattern (
unit.Insert()
). If you truly have a distinct domain (business) layer and persistence (data access) layer, then the domain objects would not know how toInsert()
.Take a look at the repository pattern. This pattern is better suited for establishing a distinct persistence layer. If you use this pattern, you can define an "Entity" in the persistence layer, and map your
Unit
object in the domain layer to theUnit
object in the persistence layer. AutoMapper should save you from the pain of manually mapping the domain model to the entity.