Ninject Cascading Constructor Arguments

烈酒焚心 提交于 2019-12-11 11:10:49

问题


I have a type IRoleRepository which accepts a constructor argument "database" which accepts a type of IDbRepository which itself takes a constructor argument "ConnectionStringName". I have a dependency resolver which has a GetService method and while the following code works I was hoping there would be better way to do this at Bind time vs at Get time with Ninject 3.0. Note I may have multiple IDBRepository instances each with their own "ConnectionStringName".

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

回答1:


You can use WithConstructorArgument to specify the constructor arguments together with the binding.

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

or use ToConstructor()

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



回答2:


OK I believe I found what I wanted:

By using this at Bind Time:

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

This allows me to use this at Get time:

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

This of course means I can now vary the constructor argument for IDbRepository based upon the more specific repository which the IDbRepository is being injected. eg:

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

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


来源:https://stackoverflow.com/questions/10141661/ninject-cascading-constructor-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!