Learn Injection of Control in a C# Console Application
Now that I'm working with C# MVC3, I learned that it's easier to setup Injection of Control because of several available plugins tha...

Things you should take note:
1.) There's no global.asax in a console application only the method static void Main(String[] args).
2.) You can also install Unity via NuGet command.
3.) You need a BootStrapper class where you defined all the interface-class mappings.
4.) You need a ServiceInjector class which will retrieve a class given an interface.
5.) In this example I have a GsmPhoneService class, that provides gsm functionalities like sendSms.
Here's how I implement the classes defined above: BootStrapper.cs
public static class BootStrapper { public static void Init() { ServiceInjector.Register<IGsmPhoneService, GsmPhoneService>(); } }In your mail class, in the Main(string[] args) method
public static void Main(string[] args) { BootStrapper.Init(); }ServiceInjector.cs, I think I got this somewhere
public static class ServiceInjector { private static readonly UnityContainer UnityContainer = new UnityContainer(); public static void Register<I, T>() where T : I { UnityContainer.RegisterType<I, T>(new ContainerControlledLifetimeManager()); } public static void InjectStub<I>(I instance) { UnityContainer.RegisterInstance(instance, new ContainerControlledLifetimeManager()); } public static T Retrieve<T>() { return UnityContainer.Resolve<T>(); } }How you will retrieve the class given an interface
IGsmPhoneService _gsmPhoneService = ServiceInjector.Retrieve<IGsmPhoneService>();
Post a Comment