I use Enterprise Library’s Unity for my Inversion of Control container. I also use constructor based injection when writing my own services, repositories, and objects; this is the cleanest form of injection IMHO. All my classes usually have one constructor, so I rarely run into a problem with overloaded constructors, but other libraries don’t usually follow this convention (rightfully so, not everyone does IoC). I am currently working on a project using Rob Conery’s awesome SubSonic 3, but I ran into a little speed bump.

11-9-2009 11-37-02 AM

oh jeez! So I have a class that has more than one constructor and I need Unity to pick the right constructor. If you are familiar with Unity then the bottom code will look familiar.

            container.RegisterType<IUsersService, UsersService>()
                     .RegisterType<IUsersRepository, SubSonicUsersRepository>()
                     .RegisterType<IPasswordSecuringService, HashingPasswordSecuringService>()
                     .RegisterType<IRepository, SimpleRepository>();

So how do you pick the constructor you want. Well it’s simple, you just have to let Unity know by configuring your container.

            container.RegisterType<IUsersService, UsersService>()
                     .RegisterType<IUsersRepository, SubSonicUsersRepository>()
                     .RegisterType<IPasswordSecuringService, HashingPasswordSecuringService>()
                     .RegisterType<IRepository, SimpleRepository>()
                     .Configure<InjectedMembers>()
                     .ConfigureInjectionFor<SimpleRepository>(new InjectionConstructor(SimpleRepositoryOptions.Default));

You’ll notice we have to say what we are configuring. In this instance we want to configure an injected member. The next step is to pick the target, the concrete target, which is SubSonic’s SimpleRepository. Finally, we create a InjectionConstructor class which will hold all of our parameters for the constructor.  Again, I rarely use this feature within my own code so I forget it and have to go looking for it in old code. Hopefully blogging about it will keep it fresh in my mind or at the very least I know where to look now.

Hopefully this helps.