2012-04-13 129 views
1

我有一个IRoleRepository类型,它接受一个构造函数参数“database”,它接受一种IDbRepository,它本身带有一个构造函数参数“ConnectionStringName”。我有一个依赖解析器,它有一个GetService方法,虽然下面的代码工作,但我希望有更好的方法来做到这一点在绑定时间与Ninject 3.0获取时间。注意我可能有多个IDBRepository实例,每个都有自己的“ConnectionStringName”。Ninject级联构造函数参数

_repository = EngineContext.Current.GetService<IRoleRepository>(
         new ConstructorArgument("database", 
          EngineContext.Current.GetService<IDbRepository>(
           new ConstructorArgument(SystemConstants.ConnectionStringName, SystemConstants.ConfigurationDatabase)))); 

回答

0

OK,我相信我找到了我想要的东西:

通过使用这种在绑定时:

  Bind<IDbRepository>().To<SqlServerRepository>() 
      .WhenInjectedInto<IRoleRepository>() 
      .WithConstructorArgument(SystemConstants.ConnectionStringName, SystemConstants.ConfigurationDatabase); 

这让我获取时间:

_repository = EngineContext.Current.GetService<IRoleRepository>(); 

这当然意味着我现在可以根据更多特定的IDbRepository注入库来改变IDbRepository的构造函数参数。例如:

  Bind<IDbRepository>().To<SqlServerRepository>() 
      .WhenInjectedInto<ITimerJobStore>() 
       .WithConstructorArgument(SystemConstants.ConnectionStringName, SystemConstants.ConfigurationDatabase); 

     Bind<ITimerJobStore>().To<TimerJobSqlStore>(); 
2

您可以用结合使用WithConstructorArgument指定构造函数的参数一起。

kernel.Bind<IDbRepository>().To<DbRepository>() 
     .WithConstructorArgument(
      SystemConstants.ConnectionStringName, 
      SystemConstants.ConfigurationDatabase); 

或使用ToConstructor()

kernel.Bind<IDbRepository>().ToConstructor(
    x => new DbRepository(
      SystemConstants.ConfigurationDatabase, 
      x.Inject<ISomeOtherDependency>()) 
+0

但我IDbRepository可能需要数的connectionStringName是,我可以有多个IDbRepository绑定每一个ConfigDB,ContentDB,DiagnosticDb等 – 2012-04-13 13:56:51