multiple registrations for constructır injection

May 5, 2015 at 7:35 AM
I've read the article about deferring the resolution of objects on msdn : MSDN Deferring the Resolution of Objects

My model is like this:
public interface IImplementMe
{
    void DoSomething();
}
public class FirstImplementation : IImplementMe
{
    public void DoSomething()
    {
        Console.WriteLine("First");
    }
}
public class SecondImplementation : IImplementMe
{
    public void DoSomething()
    {
        Console.WriteLine("Second");
    }
}
and my Service class is like this:
public class Service
    {
        private bool someCondition;
        Func<IEnumerable<IImplementMe>> myClassInstances;
        Func<Dictionary<string, IImplementMe>> myClassInstancesDictionary;

        public Service(Func<Dictionary<string, IImplementMe>> myClassInstancesDictionary)
        {
            this.myClassInstancesDictionary = myClassInstancesDictionary;
        }

        public Service(Func<IEnumerable<IImplementMe>> myClassInstances)
        {
            this.myClassInstances = myClassInstances;
        }


        public void Foo()
        {
            myClassInstances.Invoke().First().DoSomething();
            myClassInstancesDictionary.Invoke()["First"].DoSomething();
        }
    }
Usage:

When I register like below, constructor injection is successful. But I can not choose which concrete class instance to use in my service class.

So I've tried to go with a dictionary.
    IUnityContainer myContainer = new UnityContainer();


            var resolver = myContainer.Resolve<Func<IEnumerable<IImplementMe>>>();
            myContainer.RegisterType<IImplementMe, FirstImplementation>("First");
            myContainer.RegisterType<IImplementMe, SecondImplementation>("Second");

            Func<IEnumerable<IImplementMe>> fact = () =>
            {
                return resolver();
            };

            myContainer.RegisterType<Func<IEnumerable<IImplementMe>>>(
                new InjectionFactory(a => new Func<IEnumerable<IImplementMe>>(fact)));
As you can understand, I am trying to register multiple instances of an interface and shall use the proper one on run time on demand.

How should I register my types, so that I can use them in my service class by giving alias.

I know I can register them by using aliasses and resolve them by giving aliasses. But I don't want to give reference to Unity in my service class.

Or maybe there is a wiser way to do this.