no

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...

Now that I'm working with C# MVC3, I learned that it's easier to setup Injection of Control because of several available plugins that you can use straightly after install. For example the one I'm using is Unity.MVC, in Visual Studio 2010 you just have to install this plugin via NuGet and you'll be supplied a BootStrapper class where you will initialize your classes. But in c# console application I don't remember having an easy implementation :-). So I dig up my and look at how I did it, and here's how (I remember I got some parts of the code somewhere, but I don't remember exactly where :-)).

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>();

Related

c# 4875984486503526485

Post a Comment Default Comments

item