Dependency Injection with Unity
This is the most simple and short example of Dependency Injection with Unity.
Create a class with a method in it wich we are going to fire from another class ( the dependent class ), extract a interface from the class and let the inherit from this interface:
Constructor Injection
public class TestDependency : ITestDependency { public void TestDependencyMethod() { System.Windows.Forms.MessageBox.Show("Test dependency method"); } }
Create the independend class, with a property for the dependent class and a constructor wich pass the dependend class, extract a interface from this class and the class inherit from this interface:
public class TEST : ITEST { public ITestDependency TestDepency { get; set; } public TEST(ITestDependency testdependency) { TestDepency = testdependency; } public void TestMethod() { System.Windows.Forms.MessageBox.Show("Test method"); } }
Now create an instance of a UnityContainer in the root of your application to register the types:
UnityContainer container = new UnityContainer(); container.RegisterType(); container.RegisterType ();
At the place where you need an instance of the dependend class, create the instance by resolve it from the Unity container:
TEST test = container.Resolve(TEST);
Try execute both methods to see that unity automatically create an instance of the independ class at the constructor:
test.TestMethod(); test.TestDepency.TestDependencyMethod();
Property injection
Property inection is the same as constructor injectioin with the difference that the depencey object is created on a property. If we look at the example above the depend object is passed by the constructor and we are going to change that to a property decorated with the Dependency attribute. Like this:
public class TEST : ITEST { [Dependency] public TestDependency TestDepencyProp { get; set; } public void TestMethod() { System.Windows.Forms.MessageBox.Show("Test method"); } }
Call injection
The dependend object is now injection by a method. This method has to be decorated with the InjectionMethod keyword. Example:
[InjectionMethod] public void SetTestDependency(TestDependency testdenpency) { TestDepencyProp = testdenpency; }
Well this is THE most simple example of unity on the internet I think!