gpt4 book ai didi

c# - 简易喷油器 : Cyclic Graph Error

转载 作者:太空狗 更新时间:2023-10-30 01:01:11 26 4
gpt4 key购买 nike

注册表:

container.Register<IAuthenticationHandler, AuthenticationHandler>(Lifestyle.Transient);
container.Register<IUserHandler, UserHandler>(Lifestyle.Transient);

第 1 类:

public UserHandler(IAuthenticationHandler authenticationHandler)
{
_authenticationHandler = authenticationHandler;
}

第 2 类:

public AuthenticationHandler(IUserHandler userHandler)
{
_userHandler = userHandler;
}

我明白循环问题是什么。初始化 UserHandler 时,它会注入(inject) AuthenticationHandler 实现,然后尝试创建 UserHandler 实例,然后循环开始...

我的问题是如何在(SIMPLE INJECTOR)这种情况下以及其他需要像这样注入(inject)的情况下解决这个问题?

谢谢!

更新:

function AddUser(User user){ // User Handler
_authenticationHandler.GenerateRandomSalt();
string hashedPassword = _authenticationHandler.HashPassword(user.Password.HashedPassword, salt);
}

function Authenticate(string username, string password){ // Authentication Handler
_userHandler.GetUserByUsername(username?.Trim());
}

基本上我需要调用 AuthenticationHandler 中的 UserHandler 来获取用户并验证是否存在用户。

我需要调用 UserHandler 中的 AuthenticationHandler 来获取对密码进行 salt 和散列处理的函数。

我想我可以调用存储库来获取用户,但我不应该通过服务处理程序以防在用户服务中完成更多工作

最佳答案

循环依赖往往是由SOLID引起的违反原则,因为具有太广泛接口(interface)和太多功能的类更有可能需要彼此的功能。

我相信您的情况也是如此,因为 UserHandler.AddUser 功能取决于 AuthenticationHandler.GenerateRandomSaltHashPassword功能,虽然它与 AuthenticationHandler 的功能不同(即 Authenticate),但它依赖于 UserHandler 的另一个功能。这强烈表明 IAuthenticationHandler 抽象实际上违反了 Interface Segregation Principle其实现违反了 Single Responsibility Principle .

解决方案是将 IAuthenticationHandler 及其实现拆分为多个独立的部分。例如

interface IPasswordUtilities {
// NOTE: I believe GenerateRandomSalt is an implementation detail;
// it should not be part of the interface
string HashPassword(string plainPassword);
}

interface IAuthenticationHandler {
void Authenticate(string username, string password);
}

class PasswordUtilities : IPasswordUtilities {
// implementation
}

class AuthenticationHandler : IAuthenticationHandler {
public AuthenticationHandler(IUserHandler userHandler, IPasswordUtilities utilities) {
...
}
}

class UserHandler : IUserHandler {
public UserHandler(IPasswordUtilities utilities) { ... }

public void AddUser(User user) {
string hashedPassword = _utilities.HashPassword(user.Password.HashedPassword);
}
}

这将优雅地解决您的问题,因为您:

  • 通过将部分逻辑提取到更小、更集中的类中来消除循环依赖
  • 通过修复 SRP 和 ISP 违规,您可以使您的代码库更易于维护。

最终图表将如下所示:

new AuthenticationHandler(
new UserHandler(
new PasswordUtilities()),
new PasswordUtilities());

关于c# - 简易喷油器 : Cyclic Graph Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41071590/

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