问题
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