Ninject依赖项解析器以及构造函数中的运行时对象

时间:2014-05-14 07:55:21

标签: c# dependency-injection ninject

我有一个工厂,它创建我的基类的子实例,基类构造函数包含我想要解析的接口,但也包括运行时对象(我构建它们是动态的)。我如何用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的接口。这可能吗?或者我必须从构造函数中取出我的对象吗?

1 个答案:

答案 0 :(得分:0)

怎么样

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

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