Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to keep things like connectionstrings in an IoC pattern?

In my everlasting quest to suck less I'm currently checking out mvc Turbine to do the IoC dirty work.
I'm using the mvc Turbine nerd dinner example as a lead and things look rather logical thus far. Although I'm refering to the turbine project here, I'm guessing the philosophy behind it is something general to the pattern Safe for some reading and the rare podcast, I am new to the IoC concept and I have a few questions.

So far I have a IServiceRegistration entry for each IRepository I want to register
For example:

public class UserRepositoryRegistration : IServiceRegistration
{
    public void Register(IServiceLocator locator)
    {
        locator.Register<IUserRepository, UserRepository>();
    }
}

The concrete implementation of the IUserRepository needs some configuration though. Something like a connection string or in this case a path to the db4o file to use.

Where and to who should I supply this information?

like image 776
Boris Callens Avatar asked Dec 02 '09 16:12

Boris Callens


2 Answers

Both Robert and Lucas hit the nail on the head with their answers. All the "extra stuff" for the account would live within the UserRepository class. This is currently the way the Turbine ND is implemented.

However, nothing stops you from creating a new class called ConnectionStringProvider that can then be 'injected' in your UserRepository which will provide the connection string (whether it be hard coded or read from a config file.

The code can be as follows:

public class ConnectionStringProvider {
    public string ConnectionString {
        get{
             // your impl here
        }
    }
}

public class UserRepository {
   public UserRepository(ConnectionStringProvider provider){
        // set internal field here to use later
        // with db connection
   }
}

From here, you add a registration for ConnectionStringProvider within UserRepositoryRegistration class and Turbine will handle the rest for you.

like image 171
Javier Lozano Avatar answered Oct 03 '22 02:10

Javier Lozano


In general, this is solely the concern of the concrete UserRepository that requires the connection string or database path. You would do just fine by dropping the path in the application configuration file and having your concrete repository pull out the configuration data directly.

Not all repositories are going to require this information, which is one of the reasons you have the abstraction in the first place. For example, a fast in memory concrete IUserRepository will not require a path to the database or likely any additional configuration to work.

like image 22
Robert Venables Avatar answered Oct 03 '22 02:10

Robert Venables