工厂模式C#与autofac

时间:2015-02-27 08:31:05

标签: c# dependency-injection autofac factory-pattern

我想使用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;
    }
}

此外,实现IPeople的类应该是依赖注入的好处,例如,CityPeople构造函数应该注入一个IRepository,村民应该注入一个IService,等等......

我该怎么做?

提前感谢您的回答

0 个答案:

没有答案