Eric's Blog

Day to day experience in .NET
Welcome to Blogs @ IRM Sign in | Join | Help
 Search

Disclaimer

The content of this site is my own personal opinion and does not in any way represent my employer, it's subsideries or affiliates. These postings are provided "AS IS" with no warranties, and confer no rights.

This Blog

Dependency Injection: Policies

You can use policies to affect how the strategies performs their tasks in ObjectBuilder. For example, for the SingletonStrategy to consider any object to be a singleton you need to use the SingletonPolicy. Since policies affect how strategies do their work, it's easier to create more general purpose strategies, that are then informed of the details through policies.
There are two ways to set policies. One is through the Policies property of the Builder object and the other is by using the transientPolicies parameter of the BuildUp method. The policies applied through the transientPolicies argument will always take presence over the policies set on the Policies collection property. Internally the object builder (aka the classes derived from ReflectionStrategy) detects attributes like CreateNew and Dependency and creates policies (for example PropertySetterPolicy) of them.
Now, lets look at an example. The class below has two construtors, one that is used normally, but sometimes another View opens the CustomerView and then wants to directly open a specific customer and for that case we have a second constructor, which take the customerId as parameter.
 
public partial class CustomerView : Form, ICustomerView
{
    [InjectionConstructor
()]
    public
CustomerView()
    {
        InitializeComponent();
    }

    public CustomerView(int
customerId)
        : this
()
    {
        //Get the customer
    }
}
 
When this class is instantiated through the default setup of the Builder object, the constructor marked with the InjectionConstructor attribute will be used (as I blogged about here). With a little help of policies this can be changed though, so that the constructor that takes the customerId as a parameter will be called instead.
 
PolicyList policies = new PolicyList();

ConstructorPolicy policy = new ConstructorPolicy
();
policy.AddParameter(new ValueParameter(typeof(int
), 12));
policies.Set<ICreationPolicy>(policy, typeof(CustomerView), null
);

CustomerView form = Builder.BuildUp<CustomerView>(null, null, null, policies);
 
Here a ConstrutorPolicy is set up and added to a PolicyList. By passing this to the transientPolicies argument of the Buildup method this will be used instead of the default creation policy.
 
Published den 25 augusti 2006 09:13 by ericqu

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems