2009 Advent Calendar December 13th

One problem I see with how ImportantProvider turned out yesterday is that I have to give it the ImportantObject to provide. Hence I cannot be sure that all use of the ImportantObject is protected by the provider in the future. It is still too easy to bypass the thread safe ImportantProvider. We can fix this by using generics:

1: public class ImportantProvider<T> where T : ImportantInterface,new()
2: {
3: private T _importantObject = new T();
4: private Lock _lock;
6: public ImportantProvider(Lock aLock)
7: {
8: _lock = aLock;
9: }
11: public Transaction Transaction
12: {
13: get
14: {
15: return new Transaction(_importantObject, _lock);
16: }
17: }
18: }

And here is an example of how it is used in the tests:

1: _importantProvider = new ImportantProvider<DummyObject>(_lock);

Combine this by making the ImportantObject internal and keep it in an assembly with the provider and we know that nobody will use ImportantObject in an unsafe way (from a thread safety perspective).

Comments (0)

Skip to main content