IClock

Up until recently I used to write my own IDateTimeService interface and DateTimeService implementation, the idea being that instead of creating a hard dependency on System.DateTime, I could inject a wrapper service to improve testability.

However, it looks like Orchard already has a similar interface, called IClock.

The IClock interface provides access to the current date and time of the system as well as some methods that yield volatile tokens.

Although you could simply use the DateTime class to get the current date and time, it is good practice to decouple your classes from system dependencies. This decoupling greatly improves testability of your class.

Using the IClock is easy:

using System;
using Orchard.Services;
 
namespace Orchard.Docs.Misc
{
    public class ClockDemo
    {
        private readonly IClock _clock;
 
        public ClockDemo(IClock clock) {
            _clock = clock;
        }
 
        public DateTime GetCurrentTime() {
            return _clock.UtcNow;
        }
    }
}

 

When testing this class, just pass in a mocked version of IClock.

2 comments

  • ... Posted by Offshore Development Posted 04/26/2012 07:10 AM [http://mindinventory.com/]

    This code is help full for me and my friend.I'm refer to my all friend to visit site.

  • ... Posted by Offshore Development Posted 04/26/2012 07:10 AM [http://mindinventory.com/]

    This code is help full for me and my friend.I'm refer to my all friend to visit site.

Leave a comment