Binding recurring connection string constructor parameters using DI

巧了我就是萌 提交于 2020-01-05 12:07:16

问题


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

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