如何重构静态类以使用依赖注入?
我继承了一些具有带有所有静态方法的 AuthenticationManager 类的代码。
我引入了 DI 并想要添加一个带有依赖项 UserController 的构造函数,
UserController _userController;
public AuthenticationManager(UserController userCont)
{
_userController = userCont;
}
现在我收到编译时错误,因为从静态方法引用了非静态变量。您的最佳实践建议是什么,以使其能够对此类和调用代码进行最小的更改?
我们使用 SimpleServiceLocator 作为 IOC 容器。
I've inherited some code that has a class AuthenticationManager with all static methods.
Im introducing DI and wanted to add a constructor that took a dependency UserController
UserController _userController;
public AuthenticationManager(UserController userCont)
{
_userController = userCont;
}
Now Im getting the compile time error as a non-static variable is referenced from a static method. What would your best practice recommendation be to get this to work with the minmimal changes to this class and the calling code?
We're using the SimpleServiceLocator as the IOC container.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于该类在整个代码中使用的频率。您可能需要创建一个
IAuthenticationManager
接口,其中包含与您想要用实例方法替换的静态方法相匹配的方法。然后,您可以创建一个实现该接口的 AuthenticationManager 类,并通过其构造函数接受 UserController 依赖项。然后,您需要将所有静态方法调用站点替换为实例方法。您可能希望通过构造函数或属性将
IAuthenticationManager
注入到类中。如果需要,您还可以将IAuthenticationManager
作为参数传递给方法(在调用站点)。不幸的是,替换静态方法需要大量重构。不过,这是值得的。它打开了单元测试的大门。
请记住,您始终可以通过提取静态方法之一的接口来一次重构一个方法。一次执行一个方法,以逐步进行重构(换句话说,每个方法都有自己的接口)。
如果可以的话,我建议您看一下这本书:有效地使用遗留代码。一本很棒的书,涵盖了像这样的所有情况。
Well it depends on how often the class is used throughout the code. You'll likely want to create an
IAuthenticationManager
interface that includes methods that match the static methods you want to replace with instance methods. Then you could create anAuthenticationManager
class that implements the interface, and accepts theUserController
dependency via its constructor.You would then need to replace all the static method call-sites the instance methods. You would probably want to inject an
IAuthenticationManager
into the classes via a constructor or a property. If need-be, you could also pass anIAuthenticationManager
to the methods (at the call-sites) as a parameter.Unfortunately replacing static methods takes quite a bit of refactoring. It is worth the effort though. It opens up the door for unit-testing.
Keep in mind that you can always refactor one method at a time by extracting an interface for one of the static methods. Do each method one at a time to take a step-wise approach to your refactoring (in other words, each method gets its own interface).
I would recommend taking a look at this book if you can: Working Effectively With Legacy Code. Great book that covers all sort of situation like this one.