gpt4 book ai didi

c# - 使用贫血域模型的服务之间的循环引用

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:25 25 4
gpt4 key购买 nike

我正在从事一个业务复杂的项目。考虑两个类:AccountService 和 SchoolService

我正在使用 Unity 和 Web API 的依赖解析器在构造函数中实现依赖注入(inject)。

学校服务在某些方面使用了账户服务,账户服务也使用了学校服务。所有这些都是项目业务所需要的。这将导致循环依赖,并且无法将方法从一个类移动到另一个类。

能否请您提供有关如何解决此问题的任何想法?

这是一个例子:

public class SchoolBLC : ISchoolBLC
{
public School GetSchool(int schoolId)
{
...
}

public bool RenewRegistration(int accountId)
{
bool result = true;

IAccountBLC accountBLC = new AccountBLC();
// check some properties related to the account to decide if the account can be renewed
// ex : the account should not be 5 years old
// check the account created date and do renewal

return result;
}
}

public class AccountBLC : IAccountBLC
{
public void ResetAccount(int accountId)
{
ISchoolBLC schoolBLC = new SchoolBLC();
School accountSchool = schoolBLC

// get the school related to the account to send a notification
// and tell the school that the user has reset his account
// reset account and call the school notification service
}

public Account GetAccount(int accountId)
{
...
}
}

两个类相互引用,项目中70%的BLC都是这种情况。

最佳答案

如果你绝对必须那样做,你可以有一个接口(interface)来执行你的 IoC 逻辑并将其解析为包装 Unity 分辨率的实现,例如

public interface ITypeResolver
{
T Resolve<T>();
}

然后您可以将该接口(interface)传递给构造函数中的两个服务,并在使用它之前在构造函数之外使用它来延迟解析另一个服务。

这样,当两个服务都被初始化时,它们将不会直接依赖于另一个服务,只依赖于 ITypeResolver

关于c# - 使用贫血域模型的服务之间的循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40094088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com