using System; using Microsoft.Practices.Unity; namespace DependencyInjectionSample { public interface IUnityClass { void HelloWorld(); } public class UnityClass : IUnityClass { public void HelloWorld() { Console.WriteLine("Hello!"); } } /// <summary> /// This class is used to manage dependency injection using Unity. /// It Manages containers and configurations. /// </summary> internal static class DependencyInjection { private static IUnityContainer InitUnityContainer() { IUnityContainer myContainer = new UnityContainer(); //Register types myContainer.RegisterType(typeof (IUnityClass), typeof (UnityClass)); //... return myContainer; } public static T Resolve<T>() { IUnityContainer myContainer = InitUnityContainer(); return (T) myContainer.Resolve(typeof (T)); } } public class HelloWorld { public HelloWorld() { var di = DependencyInjection.Resolve<IUnityClass>(); di.HelloWorld(); } } }
2014-11-04
Dependency Injection - Hello World
Here is a simple implementation of Dependency Injection. UnityContainer is initialize in code but you can use configuration file if you like.
Subscribe to:
Posts (Atom)