Another use for Guard
Posted by Nicholas Blumhardt | November 11, 2007 08:30
I wrote earlier about a handy utility class based on IDisposable.
Well, I think I'm going to end up using this one more than I expected. I did some refactoring of ContainerBuilder last night and changed one of the APIs I've never been happy with. The WithScope() syntax is fine but when registering a bunch of factories the typing can get repetitive. So, previously, to change the default instance scope you could do this:
var oldDefault = builder.DefaultInstanceScope; builder.DefaultInstanceScope = InstanceScope.Factory; // Register a bunch of factories // then revert to the saved default builder.DefaultInstanceScope = oldDefault;
This is a bit repetitive in itself, and to be truly correct requires a try/finally block.
The new syntax is:
using (builder.SetDefaultScope(InstanceScope.Factory))
{
// Register factories
}
// At the end of the using block, the old default is reinstated
The C++ warriors of old will recognise this pattern. What's nifty is the implementation of SetDefaultScope():
public IDisposable SetDefaultScope(InstanceScope scope)
{
var oldValue = _defaultInstanceScope;
_defaultInstanceScope = scope;
return new Guard(() => _defaultInstanceScope = oldValue);
}
Pretty minimal, I think.
Comments
There are no comments on this article.
Disclaimer: These articles represent the opinions of the authors and may not match the official position of Ubik Systems Pty. Ltd. Confirmation should be sought on all matters involving professional advice.

Your Comment
Reset