Simple Injector,想要根据运行时值有条件地注入

时间:2018-03-09 10:19:29

标签: c# .net dependency-injection simple-injector strategy-pattern

说我有以下类定义:

public class CreateThingyController : ICreateThingyController
{
    private readonly ICreateThingyHandler handler;

    private ISomeBusinessRuleBehaviourDependingOnFlag rule;

    public CreateThingyController(ICreateThingyHandler handler)
    {
        handler = handler;
    }

    public void CreateThingy(string something, bool flag)
    {
         if(flag) rule = new BlaImplementation()
         else rule = new BoehImplementation 
    }
}

我真的不喜欢在运行时设置这样的行为,所以我想利用SimpleInjector。但是因为我只知道在运行时要选择什么,取决于某些变量,我不知道如何处理这个......

非常感谢任何帮助!

编辑:哦,哇,我现在才开始使用DI容器的好处。太棒了。

1 个答案:

答案 0 :(得分:2)

您可能需要在此处查看工厂模式。

public class BusinessRuleBehaviourFactory : ISomefactory
{
    public ISomeBusinessRuleBehaviourDependingOnFlag Create(string flag)
    {
        if (flag == "something")
            return new BlaImplementation();
        else if (flag == "something else")
            return new BoehImplementation();

        return new DefaultImplementation();
    }
}

然后你就把你的工厂注入你的班级

public CreateThingyController(ICreateThingyHandler handler, ISomeFactory someFactory)
{
    handler = handler;
    factory = someFactory;
}