How to use the concept of unavailable dependencies

Feb 12, 2010 at 8:40 AM


I have a situation where some dependencies might be unavailable at times. However, I am finding it difficult to detect this in the consumer object. How should I implement such a scenario?

E.g. I have a Widget with a constructor Widget(Doodad foo). In some system configurations Doodad might not be available, so I want Widget to detect this and adjust its behavior accordingly.

It would be nice here if I could get null injected if Doodad is not registered. However, Unity defaults to creating an instance of Doodad, even if it is not registered. What should I do here? How should I handle this scenario?




Feb 12, 2010 at 6:28 PM

The trick here would be to have Widget depend not on Doodad, but IDoodad (or make Doodad an abstract class). This is generally a good idea anyway.

Then, at least in Unity 2.0, you can use an optional dependency, then you'll get null if the Doodad can't be created for whatever reason. For Unity 1.2, look at the WebCast Demos page; in the extensibility demo there's an implementation of optional dependencies in there.