Ok, this is just a cool little feature I found in Ninject today and I am 100% sure I may be the last person on the planet to find this but who cares.
today as I was trying to get IoC implemented in our application at work I ran across the need to bind a type to an existing singleton in our application. The reason for this need is 2 fold:
- I am not willing to take on the risk at this point of changing the ENTIRE application to utilize IoC
- This is our RIA services domain context and I do not have enough knowledge in RIA services to know a better way to do this
So how do you bind a type to an existing method (or property)?
- Make sure that you have the general convention based bindings setup correctly within Ninject.
- Rebind your time and point it to the method you want to use
To Rebind you simply should do
ninjectKernel.Rebind<DomainContext>().ToMethod(x => MyClass.DomainContext);
In the above code what we are doing is Rebinding the DomainContext type to the Method on the MyClass instance. This will notify Ninject to not try to create a new instance of DomainContext but rather it will invoke the method, or in my case property, on my class.
I just thought this was kinda cool and wanted to share.
Till next time,
06-30-2011 7:57 AM