28 October 2007

Decorating Services

by mo

So tonight I decided to spend some time playing with services, principals, identities, and loggers. On Thursday at work a client wanted to be able to log several different events in a system. I remember a while back reading an article on MSDN byOren on Ioc, and I thought I would try to roll something out just to get a feel for who it could work. I still have a lot to learn when it comes to IoC so I put that aside for now.

It all starts at the AuthenticationService in a method called CheckCredentials. It looks something like…

  public bool CheckCredentials(string userName, string password) 
    IUser user = _repository.FindBy(userName);
    if (IsMatch(user.PasswordHash, password)) 
      return true;
    return false;

This method checks the repository for the user with the matching username and checks to see if the password given matches the password hash for the user in the repository. If it does, a principal is created and applied to the current thread. Passwords really shouldn’t be held in memory for long, and would probably better be transferred or computedas a hash, so that the actual password exposure is limited. (There’s also a “SecureString” type which I haven’t spent much time looking at, but sounds promising!)

Now if I wanted to log all login attempts I can extend this service with a AuthenticationLoggerService decorator. That looks like…

  public class AuthenticationLoggerService : IAuthenticationService 
    public AuthenticationLoggerService( IAuthenticationService service, ILogger logger ) 
      _service = service;
      _logger = logger;

    public bool CheckCredentials( string userName, string password ) 
      _logger.Write( "User Login Attempt: " + userName );
      return _service.CheckCredentials( userName, password );

    private readonly IAuthenticationService _service;
    private readonly ILogger _logger;

All this type does is log information and delegate to the actual type.

“The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide flexible alternative to subclassing for extending functionality.” - Head First Design Patterns

Read more in…

Head First Design Patterns (Head First)
by Elisabeth Freeman, Eric Freeman, Bert Bates, Kathy Sierra

Read more about this title…

PlayingWithServices.zip (2.28 MB)

csharp designpatterns