mercredi 13 juillet 2016

Dependency Injection - Using a static dependency field instead of injecting to each object

What is wrong with having the dependency object as a static field in a static class instead of injecting it to each object that depends on it through constructor?

public static class Dependencies
{
    public static IUsersRepository Users;
    ...
}
//Use in a method that depends on Users Repository
var users = Dependencies.Users.GetUsers();    

VS.

public class UserController
{
    private IUsersRepository _users;
    public UserController(IUsersRepository repo)
    {
        this._users = repo;
    }
    public List<User> GetCustomUsers()
    {
        var users = this._users.GetUsers();
        ...
    }
}

Aucun commentaire:

Enregistrer un commentaire