问题
I'm looking for advice on how best to bind a couple of connection strings which recur throughout my dependencies.
Currently I have (using ninject):
Bind<IFoo>().To<SqlFoo>()
.WithConstructorArgument("db1ConnStr", db1ConnectionString)
.WithConstructorArgument("db2ConnStr", db2ConnectionString);
Bind<IBar>().To<SqlBar>()
.WithConstructorArgument("db1ConnStr", db1ConnectionString)
.WithConstructorArgument("db2ConnStr", db2ConnectionString);
etc.
which obviously is not the most elegant code.
Is there a way to bind the value of db1ConnectionString to every string constructor parameter named "db1ConnStr"?
回答1:
I would create a class which holds the connection strings:
public class ConnectionStringProvider
{
public string Db1ConnectionString { get; set; }
public string Db2ConnectionString { get; set; }
}
Note: You can also create an interface IConnectionStringProvider
for it if you want.
Then the classes SqlFoo
and SqlBar
can use it as a dependency
public class SqlFoo
{
public SqlFoo(ConnectionStringProvider connectionStringProvider)
{
//do something with connectionStringProvider.Db1ConnectionString
}
}
And the registration would look like this:
Bind<ConnectionStringProvider>().ToConstant(
new ConnectionStringProvider
{
Db1ConnectionString = db1ConnectionString,
Db2ConnectionString = db2ConnectionString,
});
Bind<IFoo>().To<SqlFoo>();
Bind<IBar>().To<SqlBar>();
来源:https://stackoverflow.com/questions/10344568/binding-recurring-connection-string-constructor-parameters-using-di