如何重构静态类以使用依赖注入?

发布于 2024-12-22 09:00:58 字数 366 浏览 1 评论 0原文

我继承了一些具有带有所有静态方法的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

两人的回忆 2024-12-29 09:00:58

这取决于该类在整个代码中使用的频率。您可能需要创建一个 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 an AuthenticationManager class that implements the interface, and accepts the UserController 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 an IAuthenticationManager 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文