Introduction
In this article, Property Injection (and Method injection) will be demonstrated. This will be done using the unity container.
Background
Code for this article has been written using Silverlight 3 and Unity Application Block 1.2 for Silverlight. The XAML and its output are very similar to a previous article (on Constructor Injection). Most of the concepts mentioned here are also similar to the older article.
Using the Code
Again, the two numbers that are going to be added are represented as interfaces in the sample code. We are then implementing these interfaces in two number classes (one each for the numbers).
public interface INumberA {
int NumA {get;set;}
}
public class NumberA:INumberA {
private int intNumA;
public int NumA
{
get {return intNumA;}
set { intNumA = value; }
}
}
The Total
class this time does not contain a constructor. Instead it contains two properties. These properties are actually the number interfaces the total "depends" on.
The Dependency attribute is important here. This is what tells Unity what types this class depends on.
[Dependency()]
public INumberA PropNumA { get { return this.objA; } set { this.objA = value; } }
[Dependency()]
public INumberB PropNumB { get { return this.objB; } set { this.objB = value; } }
Instead if we were using method injection, this is what this code would look like:
[InjectionMethod]
public void initialize(INumberA objA, INumberB objB) {
this.objA = objA;
this.objB = objB;
}
A method with the InjectionMethod
attribute is created. The dependencies are set to be the two parameters.
The Total
class also implements the INotifyPropertyChanged
interface and some properties that are used in binding to the XAML.
public int Sum {
get {
return intSum;
}
set {
if (intSum != value) {
intSum = value;
OnPropertyChanged("Sum");
}
}
}
public int NumA {
get {
return objA.NumA;
}
set {
if (objA.NumA != value) {
objA.NumA = value;
OnPropertyChanged("NumA");
GetSum(objA.NumA, NumB);
}
}
}
public int NumB {
get {
return objB.NumB;
}
set {
if (objB.NumB != value) {
objB.NumB = value;
OnPropertyChanged("NumB");
GetSum(NumA, objB.NumB);
}
}
}
private void GetSum(int num1, int num2)
{
Sum = objA.NumA + objB.NumB;
}
Hardly anything changes in the xaml.cs code behind file.
IUnityContainer container = new UnityContainer()
.RegisterType<INumberA, NumberA>()
.RegisterType<INumberB, NumberB>();
this.DataContext = container.Resolve<Total>();
The total is displayed and calculated once the application is run and the numbers are entered on the web page.
Points of Interest
Note that nothing changes in MainPage.xaml.cs, i.e. no matter what injection style is used, for this sample, the client remains the same.
History
- Initial revision - 23rd August, 2009