首页 / C# / c# – 简单注入器:循环图错误
c# – 简单注入器:循环图错误
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 简单注入器:循环图错误,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2576字,纯文字阅读大概需要4分钟。
内容图文
![c# – 简单注入器:循环图错误](/upload/InfoBanner/zyjiaocheng/796/4147d5241ecc4f1d8575fd7cc111da74.jpg)
注册地:
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时,它会注入AuthenticationHandler实现,然后尝试创建UserHandler实例并开始循环…
我的问题是我如何解决(简单注射器)这种情况以及我需要注射的其他情况?
谢谢!
更新:
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和hash密码的函数.
我想我可以调用存储库来获取用户,但是如果在用户服务中完成更多的操作,我不应该通过服务处理程序
解决方法:
循环依赖性通常是由SOLID原则违规引起的,因为具有过宽接口和功能太多的类具有更高的需要彼此功能的可能性.
我相信在你的情况下也是这种情况,因为UserHandler.AddUser功能依赖于AuthenticationHandler.GenerateRandomSalt和HashPassword功能,而它与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# – 简单注入器:循环图错误全部内容,希望文章能够帮你解决c# – 简单注入器:循环图错误所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。