简单注入器,希望根据运行时值有条件地注入

Simple Injector, want to inject conditionally based on runtime value

假设我有以下 class 定义:

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 容器的好处。很棒的东西。

您可能想在这里查看工厂模式。

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();
    }
}

然后你只需将你的工厂注入你的 class

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