I'm writing a class that works with an API Client object that sometimes becomes corrupted and has to be recreated from inside the object that uses it. What is the best way to do this using Dependency Injection? I'm hesitant to call the DI framework from inside the class since it makes my code dependent on it.
public class MyObject
{
protected IMyAPIClient Client { get; set; }
public MyObject(IMyAPIClient client)
{
Client = client;
}
protected async Task<ReturnType> Run<ReturnType>(Func<Task<ReturnType>> action, int attempt = 1)
{
try
{
return await action();
}
catch(Exception exception)
{
Client = await GetNewClient();
if(attempt > MAX_ATTEMPTS)
{
throw new Exception($"Failed {attempt} times", exception);
}
return await Run(action, attempt++);
}
}
protected async Task<IMyAPIClient> GetNewClient()
{
// what to do here?
}
}
One solution that I came up with was to implement IMyAPIClient in a class that knows the type of IMyAPIClient and recreates it, thus circumventing the DI framework. I wonder if this is sensible or if there is a better way to do it?
Aucun commentaire:
Enregistrer un commentaire