In my last post I made a walkthrough of the Locator. The Dependency attribute is used to make searches in the Locator and then have the property (or parameter) set to the result of the search. In that previous post I used an example of an application object model like in Word, Excel and other Office applications, with an Application object as the root and Window objects in a Windows collection. Let's look at an example with the Dependency attribute, where the Form/View wants to get a reference to the Window object.
[Dependency()]
public Window Window
{
get { return window; }
set { window = value; }
}
By just adding the Dependency attribute to the property, it will make the builder search in the Locator of an object of the property's type. There are four properties on the Dependency attribute to control its behavior and all are optional. Three of them are closely related to the Locator and DependencyResolutionLocatorKey that I covered in the last post. It is SearchMode, CreateType and Name. The SearchMode determines if only the current Locator or also it's parents Locator should be searched. The Name is the string identifier that can be used with object builder, and CreateType is the type it's registered under. The fourth property is called NotPresentBehavior and determines what should happen if the dependent object could not be found in the locator. The choices are to throw an exception, return null or create a new object.