First you will have to create the class with the properties that need to be injected.
1: public class Person
2: {
3: private int ival;
4:
5: //Dependency attribute is required for Unity to know that this is the property to
6: //inject with the registered object.
7: [Dependency]
8: public int IVal
9: {
10: get { return ival; }
11: set { ival = value; }
12: }
13:
14: public override string ToString()
15: {
16: return IVal.ToString();
17: }
18: }
Then create the Unity container that will be configured to inject the dependency.
1: IUnityContainer unityContainer = new UnityContainer();
You will now need to configure the UnityContainer to register the object required by the Person class.
1: //Person - class to assign the injected member to
2: //IVal - member name of class Person
3: //10 - Value to be assigned to IVal
4: unityContainer.Configure<InjectedMembers>()
5: .ConfigureInjectionFor<Person>(new InjectionProperty("IVal", 10));
Doing this and using the Person class won't automatically assign the value to the member e.g.
1: Person p = new Person();
2:
3: //This will output 0 (zero) as IVal is unassigned, causing the default for int to be displayed.
4: Console.WriteLine("Value of IVal is {0}", p.ToString());
To allow for the property to be resolved, you will have to resolve the object using Unity's resolve method.
1: Person p = unityContainer.Resolve<Person>(); //Create Person and assign a value to IVal.
2:
3: //This will give a value of 10 as the property is assigned correctly.
4: Console.WriteLine("Value of IVal is {0}", p.ToString());
Getting property injections working correctly, took a while as I had to start using Factory classes to create and initialize classes required for my domain. Using factory classes allowed me to use Unity within my unit tests to register mocked objects.