这是在运行时解决依赖关系的合适解决方案吗

Is this an appropriate solution to resolving dependencies at runtime

我有一个 class,它需要根据用户输入以不同方式处理数据。

有两个处理器class都遵循相同的接口,但行为略有不同。

我的 IOC 容器正在向我的程序实例注入一个 IThingerFactory。

下面是我当前解决方案的示例。

有没有更好的方法解决这个问题?

public class Program
{
    public IThingerFactory ThingerFactory { get; set; }

    public Program(IThingerFactory thingerFactory)
    {
        ThingerFactory = thingerFactory;
    }

    public void FunctionWhichDoesStuff(int? input)
    {
        ThingerFactory.GetThinger(input).DoAThing();
    }
}

public interface IThinger
{
    void DoAThing();
}

public class DailyThinger : IThinger
{
    public void DoAThing()
    {
        throw new NotImplementedException();
    }
}

public class MonthlyThinger : IThinger
{
    public MonthlyThinger(int monthNumber)
    {
        MonthNumber = monthNumber;
    }

    public int MonthNumber { get; set; }

    public void DoAThing()
    {
        throw new NotImplementedException();
    }
}

public interface IThingerFactory
{
    IThinger GetThinger(int? number);
}

public class ThingerFactory : IThingerFactory
{
    public IThinger GetThinger(int? number)
    {
        return number.HasValue ?
            new MonthlyThinger(number.Value) as IThinger : 
            new DailyThinger() as IThinger;
    }
}

既然你强调了 IOC 的使用,我想你真正的问题是 IOC 是否可以完成这项工作。我认为 IOC 应该只在启动时用于制作静态对象图,而工厂模式(或其他模式)应该在以后使用。所以你的代码对我来说很好。