【问题标题】:Ninject dependency resolver plus runtime objects in constructorNinject 依赖解析器加上构造函数中的运行时对象
【发布时间】:2014-05-14 07:55:21
【问题描述】:

我有一个工厂,它创建我的基类的子实例,基类构造函数包含我想要解析的接口以及运行时对象(我动态构建它们)。我将如何用 ninject 解决这个问题?

这是一个 MVC 应用程序。

我的工厂:

public BaseInstallation GetInstallation(CustomerConfiguration customerConfiguration, CallerConfig callerConfig)
    {
        var resolver = System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver;

        switch (customerConfiguration.Type)
        {
           case InstallationType.Tablet:
                return resolver.GetService(typeof(InstallationTablet)) as InstallationTablet;

            case InstallationType.Full:
                return resolver.GetService(typeof(InstallationFull)) as InstallationFull;

            default:
                throw new NotImplementedException("Type not implemented yet in factory");

        }

我需要在运行时将 customerconfiguration 和 callerConfiguration 都传递给 InstallationTablet 和 Full 构造函数。

构造函数:

  public InstallationTablet(CustomerConfiguration customerConfiguration,CallerConfig callerConfig,IDBConnector dbConnector,IFileService fileService)
        : base(customerConfiguration,callerConfig,dbConnector, fileService)

我只想在启动时使用 Ninject 解析接口。这可能吗?还是我必须将我的对象从构造函数中取出?

【问题讨论】:

  • 完整安装还是平板安装,信息从何而来? CallerConfig 来自哪里?

标签: c# dependency-injection ninject


【解决方案1】:

怎么样

public static InstallationType GetInstallationType() {
   /* your logic goes here */
}

// Bindings
IBindingRoot.Bind<BaseInstallation>().To<InstallationTablet>()
            .When(ctx => GetInstallationType() == InstallationType.Tablet);


IBindingRoot.Bind<BaseInstallation>().To<InstallationFull>()
            .When(ctx => GetInstallationType() == InstallationType.Full);

当你回答我的问题时(见评论),我会扩展答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2012-01-04
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多