Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I need to create a DateTime service which returns DateTime.Now instead of using DateTime.Now directly?

I have been watching Jason Taylor presentation about Clean Architecture with ASP.NET Core (timing 35:52)

https://www.youtube.com/watch?v=dK4Yb6-LxAk&t=2134s&ab_channel=GOTOConferences

And he created a DateTimeService which returns DateTime.Now and registered via AddTransient method, he suggests using it instead of using DateTime.Now directly because in this case he doesn’t have a dependency on the machine clock.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s not clear to me why he doesn’t have a dependency in this case, could you please explain how it works?

>Solution :

If you were ever going to implement a different way for getting the current time all you would need to do is create a new implementation for your IDateTimeService instead of changing every single instance of DateTime.Now in your project.

An example would be to create a service that obtains the time with an external request or to easily create a mock for unit tests so you can properly assert results that are dependent on the date and time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading