抽象 DateTime.Current 依赖项
是否有一个 nuget 包或其他“标准”来包装您的代码与 DateTime.Now
耦合时创建的硬依赖项?
在编写自己的文章之前,我正在寻求这方面的指导。尽管这样做很简单,但我宁愿使用现有的东西(如果它已经作为某种标准)。
Is there a nuget package, or other "standard" that wraps the hard dependency created when your code is coupled to DateTime.Now
?
I'm seeking guidance on this before writing my own. Albeit that it's trivial to do so, I'd rather use something that exists if it already does as somewhat of a standard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我非常怀疑是否有任何 nuget 包可以处理如此琐碎的事情 - 一个接口和可能两个实现(“系统”时钟和一个用于测试的假时钟)。
如果您自己执行其中一项操作,我强烈考虑让时钟返回
DateTimeOffset
而不是DateTime
,或 至少让它包装DateTime.UtcNow
...DateTime.Now
是一个等待发生的问题...但是,Noda Time 包含所有开箱即用的内容。请注意,您可能不想要整个 Noda Time 只是因为这个原因...
(有一个 Noda Time nuget 包,但它肯定是预发布的。我需要在某个时候将其更新到 0.2 版本,但是不过,它仍然还没有达到v1级别......)
如果您想要一种真正的廉价且愉快的方式来表达依赖关系,您总是可以采取一个
Func
或Func
在通常表达依赖关系的地方。不过,界面方法更干净:)I very much doubt that there's any nuget package for anything quite so trivial - a single interface and probably two implementations ("system" clock and a fake one for testing).
If you're doing one of these yourself, I would strongly consider making the clock return a
DateTimeOffset
instead of aDateTime
, or at least make it wrapDateTime.UtcNow
...DateTime.Now
is a problem waiting to happen...However, Noda Time contains all of this out of the box. You probably don't want the whole of Noda Time just for this reason, mind you...
(There's a Noda Time nuget package, but it's definitely pre-release. I need to update it to a 0.2 version at some point, but it's still not at the v1 level yet. Getting there though...)
If you want a really cheap-and-cheerful way of expressing the dependency, you could always take a
Func<DateTime>
orFunc<DateTimeOffset>
wherever you normally express dependencies. The interface approach is cleaner though :)我不知道有任何 nuget 包可以做到这一点。当我遇到这个问题时,我只是创建了自己的类型,如下所示:
这样,在单元测试中,您可以轻松更改 Now 的功能以返回您想要的任何 DateTime。
I dont know of any nuget package that does this. When I've run into this problem I've simply created my own type like this:
That way in your unit tests you can easily change the functionality of Now to return any DateTime you want.
假设我们有一个方法:
我在需要
DateTime.Now
时总是采用的解决方案是:Suppose we have a method:
The solution i always employ anytime I need
DateTime.Now
is: