在构造函数中添加对象依赖解析器和运行时对象

本文关键字:对象 运行时 依赖 构造函数 添加 | 更新日期: 2023-09-27 18:03:10

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

在构造函数中添加对象依赖解析器和运行时对象

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

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