0
votes

I'm using Ninject for dependency injection in my ASP.NET MVC project. I've lot of repository classes and each class take the connection string parameter in the constructor.

Currently for each mapping I've to pass the connection string as well.

Ex.

Bind<INewsRepository>().To<NewsRepository>().WithConstructorArgument("connectionString", "Data Source=...");
Bind<IProductsRepository>().To<ProductsRepository>().WithConstructorArgument("connectionString", "Data Source=...");

Is it possible to bind the "connectionString" directly to the configuration value at a global level instead of specifying at each binding?

2

2 Answers

4
votes

My solution would be: Wrap the connectionstring in an object, say ConnectionStringWrapper and make an Interface IConnectionStringWrapper. Use the interface in your repositories and bind the ConnectionStringWrapper to the interface using Ninjects.

3
votes

This is the best I've come up with

Create extension method

    public static class IBindingExtensions
    {
         public static IBindingWithOrOnSyntax<T> WithConnectionString<T>(this IBindingWhenInNamedWithOrOnSyntax<T> binding)
         {
             return binding.WithConstructorArgument("connectionString", "Data Source=..");
         }
    }

And call it for every connection string argument binding

Bind<INewsRepository>().To<NewsRepository>().WithConnectionString();