依赖注入导致循环依赖和堆栈溢出,我做错了什么吗?
我是依赖注入领域的新手,刚刚开始开发一个使用 Unity 2.0 的项目。一切都运行良好,直到我创建了一个 MVC 服务,该服务引用另一个服务,而另一个服务又引用另一个服务。结果我得到了一个堆栈溢出异常。我理解正在发生的事情并且这是有道理的,但这让我停下来并认为我可能做错了什么。是否有最佳实践来确保这种情况不会发生?
public AccountService(IUserRepository userRepository, IAuthenticationService authService...
public AuthenticationService(IUserRepository userRepository, IAccountService accountService...
I'm new to the Dependency injection world and just started working on a project that uses Unity 2.0. Everything was working great until I created a MVC service that references another service that in turn references the other service. As a result I get a stack overflow exception. I understand what is happening and it makes sense but it made me stop and think that I might be doing something wrong. Is there a best practice for ensuring this doesn't happen?
public AccountService(IUserRepository userRepository, IAuthenticationService authService...
public AuthenticationService(IUserRepository userRepository, IAccountService accountService...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
,你的设计是错误的。您应该避免对象中的循环引用。
只需打破对象层次结构中的循环引用即可。重新思考你的设计。
Yes, your design is wrong. You should avoid circular references in your objects.
Just break this circular reference in your objects hierarchy. Rethink your design.