views:

53

answers:

2

How would you convert my current business logic layer method into IOC?

public static List<User> GetUsers()
{
    MyDBProvider db = new MyDBProvider();

    return db.GetUsers();
}
+2  A: 
List<User> users = GetUsers(new MyDbProvider());

List<User> GetUsers(IDataProvider provider){
    return provider.GetUsers();
}
Arnis L.
Should the collection List<users> also use some kind of interface?
Blankman
That depends in what format calling method expects data. Instead of List<T> you can pick User[], IList<User> IEnumerable<User> etc. IoC (inversion of control) basically means that you can change behavior of method from outside (by passing in object which will perform job you need through interfaces), not the data type what's going to be returned.
Arnis L.
A: 

I'd probably get rid of the static method and use a more object oriented approach for starters.

public class UserRepository {
    private DBProvider provider;

    public DBProvider getProvider() { return provider; }
    public void setProvider(DBProvider provider) { this.provider = provider; }

    public List<User> getUsers() { return getProvider().getUsers(); }
}

public interface DBProvider {
    List<User> getUsers();
}

public class MyDbProvider implements DBProvider { ... }
David
"public class MyDbProvider implements DBProvider { ... }" ----> "public class MyDbProvider : DBProvider { ... }". At least in c#.
Arnis L.
But the most beautiful way is to use IoC containers.
Arnis L.