在我的C#项目的循环引用 [英] Circular References in my C# projects

查看:201
本文介绍了在我的C#项目的循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:


  1. 一个项目 MyCompany.MyProject.Domain ,其中包含我的域模型,部分类(如联系)。

  1. A project MyCompany.MyProject.Domain which contains my domain model, and partial classes (such as Contact).

我想扩展(由部分类,而不是扩展方法)我的联系类属性弹头这将给我的第一个和最后一个名称的简单的URL友好的文本表示。

I want to 'extend' (by partial class, not extension method) my Contact class with a property Slug which will give me a simple URL friendly text representation of first and last name.

我有一个字符串扩展方法 ToSlug()在我的工具项目 MyCompany.MyProject.Utilities 这不正是我想要2)。

I have a string extension method ToSlug() in my Utility project MyCompany.MyProject.Utilities which does exactly what I want in 2).

问题:我的工具项目已经引用我的项目,这意味着我不能得到项目,请参阅工具项目的 ToSlug(),而不会导致循环引用的方法。

The problem: My Utility project is already referencing my Domain project which means that I can't get the Domain project to see the Utility project's ToSlug() method without causing circular reference.

我不热衷于创建另一个项目,解决这个问题,我真的想保持共享弹头逻辑。

I'm not keen on creating another project to solve this, and I really want to keep the Slug logic shared.

如何能我解决这个问题?

How can I solve this?

推荐答案

工具项目引用您的 MyCompany.MyProject.Domain 好像有点代码气味。我在这里假设这些都是在领域对象具体工作的实用程序 - 如果是这样的话,那么你为什么不包括 MyCompany.MyProject.Utilities 中的项目(当然,相应修改命名空间)?

Your Utility project referencing your MyCompany.MyProject.Domain seems like a bit of a code smell. I'm assuming here that these are utilities that specifically work on domain objects--if that's the case, then why don't you include MyCompany.MyProject.Utilities within your Domain project (naturally, modifying the namespace accordingly)?

在任何情况下,正常的方式来打破这些种依赖关系是抽象由一个项目所需成一组接口是什么,以及这些封装在一个单独的装配。这样做,虽然,确保你在做什么的概念的是正确的事情了。

In any case, the normal way to break these kinds of dependencies is to abstract what is required by one project into a set of interfaces, and encapsulate those in a separate assembly. Before doing that though, make sure that what you're doing conceptually is the right thing.

在您的具体情况,但考虑引入。接口,即, INameHolder

In your particular situation though, consider introducing an interface, viz., INameHolder:

public interface INameHolder
{
    string FirstName { get; set; }
    string LastName { get; set; }
}



然后联系工具 INameHolder INameHolder 存在于另一个组件,让我们称之为 MyCompany.MyProject.Domain.Interfaces

Then Contact implements INameHolder. INameHolder exists in another assembly, let's call it MyCompany.MyProject.Domain.Interfaces.

那么你的工具项目引用接口)也是如此,但接口不参考什么 - 循环引用是坏了。

Then your Utilities project references Interfaces (not Domain) and so does Domain, but Interfaces doesn't reference anything--the circular reference is broken.

这篇关于在我的C#项目的循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆