Convention based binding of constructor string arguments with Ninject

十年热恋 提交于 2019-12-04 04:13:26
Austin Thompson

It doesn't look like that kind of convention-based bindings is possible with Ninject right now. I had a similar question here and the suggestion was to make an interface to return the connection string and have that as the parameter. That could be tedious for many different connection strings though.

This is just a thought, but could you have an IConnectionStringProvider<T> that could use reflection to get the name of T and look up the application setting that way? Maybe like this:

public class ConnectionStringProvider<T> : IConnectionStringProvider<T>
{
    public string Value
    {
        // use reflection to get name of T
        // look up connection string based on the name
        // return the connection string
    }
}
...
public class SomeRepository:ISomeRepository
{
    public SomeRepository(IConnectionStringProvider<SomeRepository> connectionStringProvider)
    {
        this.connectionString = connectionStringProvider.Value;
    }
}

Also if that doesn't work, you could have a non-generic IConnectionStringProvider that takes a type as the argument:

public class ConnectionStringProvider : IConnectionStringProvider
{
    public string GetValueFor(Type type)
    {
        // use reflection to get name of type
        // look up connection string based on the name
        // return the connection string
    }
}
...
public class SomeRepository:ISomeRepository
{
    public SomeRepository(IConnectionStringProvider connectionStringProvider)
    {
        this.connectionString = connectionStringProvider.GetValueFor(this.GetType());
    }
}

If one of these works then they would have the advantage that they should work with any DI container.

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