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

标签 c# dependency-injection circular-dependency anemic-domain-model

我正在从事一个业务复杂的项目。 考虑两个类: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/

相关文章:

c# - WPF DataGrid 未使用绑定(bind)的 BindingList 进行更新

c# - 对 DataTable.DataSource 的 LINQ 查询

c# - 响应压缩中间件的优缺点

c# - 当您在 C# 中将父接口(interface)转换为其子接口(interface)时,依赖注入(inject)模式的目的是否丢失?

C++ 使用树避免循环依赖

C++如何拥有线程助手

c++ - dll与visual studio之间的循环依赖

c# - 将 XML 文档/注释添加到 EF 生成的类中的属性/字段

java - 在多模块环境中使用依赖注入(inject)(通过 Guice)

c# - services.AddSingleton,永远不会调用服务的构造函数