Optional Dependencies

Topics: Prism v2 - WPF 3.5
Mar 25, 2010 at 3:11 PM
I am working on a project where couple of dependency are optional. I got one module named core, which is the core of application. I got more modules/services e.g NoteReader, CoinReader, CreditCardReader. My core module need to interact/control those modules/services and I've done dependency injection in core module for those services. However the type of services I need in core are dependent on the deployment of our software e.g one deployment might need all three services and other might only need 1 or 2. How I go about achieving that in Prism. Is there a way to tell Prism I need you to inject service1/service2 but if you can't find one it is ok and inject a null object? Thanks. Qaiser.
Mar 26, 2010 at 3:56 PM

Hi Qaiser,

The scenario you are trying to achieve is viable. You can use the TryResolve extension method (explained here) of the for the IServiceLocator interface (or create your own for the Unity container) which will return null if the service cannot be resolved. Take into account that this is not viable in case you are injecting the services through property or constructor injection, as you have to explicitly use service locator to resolve the instances.

Please let me know if this helps.

Damian Schenkelman
http://blogs.southworks.net/dschenkelman

Mar 26, 2010 at 4:16 PM

Hi dschenkelman,

 

Thanks for your reply. I was initially trying to do it with constructor injection and wasn't sure how to do it. But now I am using Resolve method of UnityContainer by wrapping call in Try/Catch block and it gives me an instance if service is there otherwise throws an exception which I catch. Not an elegant solution but it works.

 

Qaiser.