【问题标题】:Ninject C# - Get concrete type at runtime from reading configurationNinject C# - 在运行时通过读取配置获取具体类型
【发布时间】:2013-07-27 18:58:09
【问题描述】:

我想根据配置值选择一个特定的绑定,为了参数,假设我有两个具体的类,称为 Action1 和 Action2。目前我正在将 Ninject 内核传递给工厂并根据它返回绑定类型。

 public class ActionFactory: IActionFactory
    {
        public IAction GetAction(IKernel kernel, string actionName)
        {
            return kernel.Get<IAction>(actionName);
        }
    }

我正在像这样绑定 Ninject 模块中的操作:

Bind<IAction>().To<Action1>().Named("Action1");
Bind<IAction>().To<Action2>().Named("Action2");

我可以绑定它而不必将内核传递给工厂吗?

如果有人有任何建议,我也有能力重构工作流程。

【问题讨论】:

    标签: c# dependency-injection ninject


    【解决方案1】:

    直接注入配置好的action,有条件地配置:

    Bind<IAction>().To<Action1>().When(ctx => IsAction1Configured());
    Bind<IAction>().To<Action2>().When(ctx => IsAction2Configured());
    

    【讨论】:

    • 您好雷莫,感谢您的回复。我不知道这对我来说是否可行(或者甚至可能使用 Ninject),因为配置是在服务中检索的复杂类型,并且绑定是在服务初始化时完成的,而无需了解配置复杂类型在堆栈的更下方的服务中检索。我不认为我想要什么是可能的,我可能需要重新考虑我的工作流程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多