[英]Circular reference between the services using the Anemic domain model
我正在從事一項業務復雜的項目。 考慮兩個類:AccountService和SchoolService
我正在使用Unity和Web API的依賴項解析器在構造函數中實現依賴項注入。
學校服務以某種方式使用帳戶服務,帳戶服務也使用學校服務。 所有這些都是項目業務所必需的。 這將導致循環依賴,並且無法將方法從一個類移到另一個類。
您能提供任何解決方法的想法嗎?
這是一個例子:
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的情況。
如果絕對必須這樣做,則可以有一個接口執行IoC邏輯並將其解析為包裝Unity分辨率的實現,例如
public interface ITypeResolver
{
T Resolve<T>();
}
然后,您可以將該接口傳遞給構造函數中的兩個服務,並在構造函數之外使用它來延遲解析另一個服務,然后再使用它。
這樣,當兩個服務都初始化時,它們將不會直接依賴於另一個服務,而僅依賴於ITypeResolver
我將按照@KMoussa的建議進行操作,但需要進行一些修改:
該項目正在使用貧血模型,因此我將使用上下文模式來延遲加載並創建任何服務,並且上下文將作為參數傳遞給服務構造函數。
public class SDPContext : ISDPContext
{
private ITypeResolver _typeResolver;
public Account CurrentUser { get; set; }
public IAccountService AccountService
{
get
{
// lazy load the account service
}
}
public ISchoolService SchoolService
{
get
{
// lazy load the schoolservice
}
}
public SDPContext(ITypeResolver typeResolver)
{
this._typeResolver = typeResolver;
}
}
public class ServiceBase
{
public ISDPContext CurrentContext { get; set; }
public ServiceBase(ISDPContext context)
{
this.CurrentContext = context;
}
}
public class AccountService : ServiceBase, IAccountService
{
public AccountService(ISDPContext context) : base(context)
{
}
public bool ResetAccount(int accountId)
{
// use base.Context.SchoolService to access the school business
}
}
public class SchoolService : ServiceBase, ISchoolService
{
public SchoolService(ISDPContext context) : base(context)
{
//this._accountService = accountService;
}
public void RenewRegistration(int accountId)
{
// use the base.Context.Account service to access the account service
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.