Decorators & ReSharper

More parts in the container tutorial series are on the way, I've
just been a little busy these last few days.



However I had a discussion with someone about decorators this week
- they eluded to them being too hard to "create" and maintain, and
that opportunities to get them wrong abound (manually writing the
code to call all the members of the inner service) - I was a little
astounded that they didn't know how to do this using
ReSharper.



So heres a quick 1 minute tutorial for those that don't know, first
an interface.


public interface IBondService
{
void Smoke50Cigarettes();
void RegisterEnemy(string name);
void GetOfBed();
bool GunLoaded();
}


Now let's write the start of our decorator.


public class BondService : IBondService
{
private readonly IBondService _innerService;

public BondService(IBondService innerService)
{
_innerService = innerService;
}
}



And then generate the rest... by going to: ReSharper
->Code->Generate...->Delegating Members


Or just type Alt-insert (if your using the default
key bindings) and select "Delegating Members".



At that point select the only option, the inner service.







And then select all the members to delegate for.







And then we get the results... joy


public class BondService : IBondService
{
private readonly IBondService _innerService;

public BondService(IBondService innerService)
{
_innerService = innerService;
}

public void Smoke50Cigarettes()
{
_innerService.Smoke50Cigarettes();
}

public void RegisterEnemy(string name)
{
_innerService.RegisterEnemy(name);
}

public void GetOfBed()
{
_innerService.GetOfBed();
}

public bool GunLoaded()
{
return _innerService.GunLoaded();
}
}


Written on May 9, 2007