问题描述
我有一个IRoleRepository类型,它接受一个构造函数参数数据库",该类型接受一个IDbRepository类型,该IDbRepository本身接受一个构造函数参数"ConnectionStringName".我有一个具有GetService方法的依赖项解析器,并且在以下代码工作时,我希望使用Ninject 3.0与在Get时相比,在绑定时有更好的方法.注意我可能有多个IDBRepository实例,每个实例都有自己的"ConnectionStringName".
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))));
推荐答案
好的,我相信我已经找到了想要的东西:
OK I believe I found what I wanted:
在绑定时间使用它:
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>();
这当然意味着我现在可以根据注入IDbRepository的更具体的存储库来更改IDbRepository的构造函数参数.例如:
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>();
这篇关于Ninject级联构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!