循环依赖最佳实践
我目前正在编写一个网络爬虫,它从互联网上检索信息。简化后看起来像这样。
数据访问项目
- 用于检索原始数据的对象
- 用于将原始数据解析为对象的对象 (!!)
- 解析器返回的实体。
现在,我正在创建实际的解析器,并且将像这样使用它:
using Application.DataAccess;
using Application.DataAccess.Entities;
namespace Application{
public class TestScraper{
public static ScrapeIt()
{
var source = DataAcces.Retriever.Retrieve("http://example.com");
DataAccess.Entities.Entity entity = DataAccess.Parser.Parse(source);
//Do stuf with source here.
}
}
}
如您所见,解析器返回一个实体。然而,这是在 DataAccess 命名空间中,但是,它没有任何意义......这是一个圆圈,我真的不知道如何解决这个问题。好吧,我可以想出一些办法,比如在这些层之间创建另一个层。
但我只是想知道,你会如何解决这个问题。以及什么是好的(或最佳实践)。
I'm currently writing a web scraper which retrieves information from the internet. Simplified it looks like this.
Data access project
- Objects to retrieve raw data
- Objects to parse the the raw data into objects (!!)
- The entities that the parser returns.
Now, I'm creating the actual parser, and I'm going to use it like this:
using Application.DataAccess;
using Application.DataAccess.Entities;
namespace Application{
public class TestScraper{
public static ScrapeIt()
{
var source = DataAcces.Retriever.Retrieve("http://example.com");
DataAccess.Entities.Entity entity = DataAccess.Parser.Parse(source);
//Do stuf with source here.
}
}
}
As you can see, the Parser returns a Entity. However this is in the DataAccess namespace, yet, it makes no sense... it´s a circle, and I don´t really know how to fix this. Well I could come up with a few things, like creating another layer between those layers.
But I just want to know, how would YOU solve this. And what is a good (or the best practice) for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过将两个类引用的内容分解到一个新类中,然后旧类都引用新类来修复循环引用。
因此,在您的情况下,您可以将实体移出 DataAccess 并移入可能由 DataAccess 和应用程序使用的新实体命名空间。
通过这样做,你开始
并结束
You can fix a circular reference by factoring out the things that both classes refer to into a new class, and then the old classes both refer to the new class.
So in your case you could move the entities out of DataAccess and into perhaps a new Entities namespace, used by both DataAccess and Application.
By doing this you start with
and end up with
数据访问层不应与域对象位于同一名称空间中。实体应该独立于不引用任何其他命名空间的程序集/命名空间中,这将允许其他基于逻辑的类(例如 DataAccess 和 Parsers)以更干净的方式自行引用实体。
Data Access Layer should not be in the same namespace as your domain objects. Entities should stand alone in an assembly/namespace that does not reference any other namespace, which will allow other logic based classes such as DataAccess and Parsers to reference the Entity on their own in a more clean manner.