Reputation: 10123
When using interfaces, where exactly should the hard implementation of each object be retrieved from. Is that done by creating a factory object for each type?
IRepository<User> userRepository = new UserRepository(connection); // Needs a dbconnection
userRepository.Create(user);
//Is this the best way?
IRepository<User> userRepository = RepositoryFactory.GetUserRepository(connection);
public static class RepositoryFactory
{
public static IRepository<User> GetUserRepository(DbConnection connection)
{
return new UserRepository(connection);
}
}
What is the best of most logical way to get a UserRepository object to work with? If I used a factory object for UserRepository, do I pass in the connection object or what is that process?
Upvotes: 1
Views: 122
Reputation: 5293
As John said you can use IOC. But that only is valid if you think you would like to have that extra layer of decoupling in your application. It would also make stubbing out/mocking a lot easier if you use an IoC. But I know that sometimes introducing a new moving piece into your project can be a pain.
The factory would indeed be a way to go. I would pass in a high level abstraction into the factory. A string or an enum that says something like as "FromADatabase" or "FromANetwork". Its up to the factory to look up the appropriate construction details for what you want (from a configuration file for example), construct the required concrete object and pass it back.
So as far as the consumers are concerned, they go to a factory and say something very high level such as I need something from there, that does this. Its up to the factory to figure out how to create that a concrete implementation of what is being asked and pass it to the caller.
Upvotes: 1
Reputation: 6553
I'm sorry if I read your question incorrectly but you might want to take a look at
Inversion of Control and Dependency Injection and see how those would fit best for what you are trying to do.
IoC: http://visualstudiomagazine.com/articles/2010/08/01/inversion-of-control-patterns-for-the-microsoft-net-framework.aspx / http://joelabrahamsson.com/entry/inversion-of-control-introduction-with-examples-in-dotnet
Dependency Injection: http://www.blackwasp.co.uk/DependencyInjection.aspx
Upvotes: 1