I am using a 3rd party client library to connect to the 3rd party's Web API. My task is to backup user data held by the 3rd party for multiple users. As such, I need to authenticate using the client library for each user prior to retrieving data. Should I have a single repository with an authenticate method, or an abstract factory that returns clients based on supplied credentials?
The authenticate method on the repository feels like a leaky abstraction. The abstract factory seems a little heavy handed creating new repository objects for each user. Is one solution objectively better than the other? Is there an alternate solution?
Code below to illustrate my point. Example1 uses a single repository, Example2 uses the abstract factory.
public interface ThirdPartyRepositoryFactory
{
ThirdPartyRepository GetRepository(string username, string password);
}
public interface ThirdPartyRepository
{
void Authenticate(string username, string password);//omit if using abstract factory
object GetUser();
}
public interface UserRepository
{
List<UserCredentials> GetUsers();
}
public class UserCredentials
{
public string Username { get; set; }
public string Password { get; set; }
}
public class Example1
{
private UserRepository _userRepository;
private ThirdPartyRepository _thirdPartyRepository;
public Example1(UserRepository userRepository, ThirdPartyRepository thirdPartyRepository)
{
_userRepository = userRepository;
_thirdPartyRepository = thirdPartyRepository;
}
public void Execute()
{
var users = _userRepository.GetUsers();
foreach (var user in users)
{
_thirdPartyRepository.Authenticate(user.Username, user.Password);
var userDate = _thirdPartyRepository.GetUser();
//persist user data
}
}
}
public class Example2
{
private UserRepository _userRepository;
private ThirdPartyRepositoryFactory _factory;
public Example2(UserRepository userRepository, ThirdPartyRepositoryFactory factory)
{
_userRepository = userRepository;
_factory = factory;
}
public void Execute()
{
var users = _userRepository.GetUsers();
foreach (var user in users)
{
var repository = _factory.GetRepository(user.Username, user.Password);
var userDate = repository.GetUser();
//persist user data
}
}
}
Aucun commentaire:
Enregistrer un commentaire