Powered by Twitter Tools.

July 2008
M T W T F S S
« Jun   Aug »
 123456
78910111213
14151617181920
21222324252627
28293031  
Chris Donnan

Create Your Badge

Chris Donnan : Programming – Brooklyn Style

software, trading, family, fun

The simplest possible DI container (part 4)

In this segment, we will discuss pushing in singletons that you have already created and adding a simple generic hook point.

Here is our starting test. We want to create something outside the container, then add it as a singleton.

This is trivial, we simple give it a delegate that returns that instance when it is called.

Here our lambda is just going to return that instance. (PS – this is a C# lambda expression, google it.).

But wait, what is wrong here… was it so trivial? Well, how about disposal? Do we want to dispose this thing when our container is disposed? I do not think so… So we can create a policy that does not dispose.

Here is a test:

Let us split our SingletonCreationPolicy into 2 parts – 1 that is the same in both cases – the creation bit, and 2 – the disposal bit we can ‘add on’ in only the case we want it in. This results in:

In our Kontainer class:

 the basic singleton creation policy is broken out (back to):

And finally, the Disposable version of the policy for ‘container managed’ singletons:

OK, so that code allows us to push singletons into the Kontainer and allows them to be disposed correctly. (Note the use of protected auto-properties. Less code - I like it).

Hook points

Many 3rd party vendors have used events as hook points for some time. I think grid control products like DevExpress’s XtraGrid have gone far and wide using events as the primary ‘hook points’ to their APIs.

In order to give similar behavior to SpringFramework’s IObjectPostProcessor, we can add an event for a similar effect. Let us start with a test:

We want to hook onto the point when a user is ‘getting’ an object. and ‘do something’ before they actually get it. In this case, we are getting drastic; we are completely replacing what the container has internally. Most usages would be more benign most likely.

We change our Get method, add a GettingObject event and allow callee’s to each have a go at the returning object. So our Kontainer class changes like:

This will happily allow callers to modify the created object and return to the ultimate caller of Get the result. It id the event listener’s perogative to elect to process the created object based either on the object itself or on the label.

So; there you have a nice way to push instances of objects into the container and a cheap hook point to ‘do stuff’ when the user calls to Get.

More soon;

Chris

Share and Enjoy:
  • del.icio.us
  • digg
  • blinkbits
  • BlinkList
  • blogmarks
  • YahooMyWeb
  • connotea
  • De.lirio.us
  • Fark
  • Furl
  • Reddit
  • scuttle
  • Shadows
  • Smarking
  • Spurl
  • TailRank
  • Wists

Responses are currently closed, but you can trackback from your own site.