0

I would like to adapt the factory pattern (from wikipedia) using autofac :

/IVSR:Factory Pattern
//Empty vocabulary of Actual object
public interface IPeople
{
    string GetName();
}

public class Villagers : IPeople
{
    #region IPeople Members

    public string GetName()
    {
        return "Village Guy";
    }

    #endregion
}

public class CityPeople : IPeople
{
    #region IPeople Members

    public string GetName()
    {
        return "City Guy";
    }

    #endregion
}

public enum PeopleType
{
    RURAL,
    URBAN
}

/// <summary>
/// Implementation of Factory - Used to create objects
/// </summary>
public class Factory
{
    public IPeople GetPeople(PeopleType type)
    {
        IPeople people = null;
        switch (type)
        {
            case PeopleType.RURAL :
                people = new Villagers();
                break;
            case PeopleType.URBAN:
                people = new CityPeople();
                break;
            default:
                break;
        }
        return people;
    }
}

In addition, classes implementing IPeople should benefits of dependency injection, for example CityPeople constructor should have a IRepository injected, Villagers should have an IService injected, and so on ...

How can I do that ?

Thanks in advance for your answers

Tim
  • 1,749
  • 3
  • 24
  • 48
  • of course I've already followed this tutorial, I don't undestand how I can register a type depending of a condition – Tim Feb 27 '15 at 08:41
  • @nvoigt That basic docs doesn't cover OP's specific scenario. His factory needs to return types based on parameter. – Sriram Sakthivel Feb 27 '15 at 08:44
  • Before doing anything else, singularise your class and variable names; they are not collections, they are individuals. – Matthew Watson Feb 27 '15 at 08:49
  • I've already seen this answer too, but the problem is that there are explicit new. Why using new with autofac ? How can I do the specific dependy injection with my providers and services ? – Tim Feb 27 '15 at 08:57
  • 1
    It's a shame this was closed, since the answer to the duplicate question is slightly different, and I have an answer which avoids the use of a switch statement... If you ask the question again but specify that you want to avoid the use of a switch statement, I could answer it. The answer uses "Keyed Services". – Matthew Watson Feb 27 '15 at 09:24
  • Thanks, Keyed services seems very good for my need. Regards – Tim Feb 27 '15 at 09:31
  • Also look at [Metadata](http://autofac.readthedocs.org/en/latest/advanced/metadata.html). I've solved the same problem using metadata. – Sriram Sakthivel Feb 27 '15 at 09:33

0 Answers0