Reputation: 63
I am having a situation that I have a common reference object that is being pass around as parameter to different operation object. It makes the code very messy to pass it around. Is there anyway to make it like a reference to every operation (like a session)? However, it is just a core code library. Using static class is not the solution.
Thanks
Upvotes: 0
Views: 237
Reputation: 161012
There are two general approaches to this that I know of:
a) Use IoC and a constructor dependency to pass in your shared object. As you mentioned if this object is used in many, many places this pollutes the interface and in many cases adds a lot of clutter.
b) Use an ambient context: Create a interface based singleton that may be accessed by the classes that need the object instance. Have a setter within the singleton that allows you to override the instance (e.g. for unit testing) so testing the code is still possible.
Upvotes: 1
Reputation: 546
Maybe the Ambient Context Pattern could work for you? http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/
Upvotes: 0
Reputation: 856
Solution 1 - You can use singletons. They guarantee that there is only one instance of the class in the running code.
Solution 2 - why don't you put the shared reference object as a property of the object with those operations? That way, each operation has access to it. You can do some fancy stuff like if the reference property is null, throw an exception or so.
Upvotes: 1