I'm very new in C# and Dependency Injection. Currently I'm working on a new project and want to do a technology step forward.
In this Project, I've three situation causing circular dependency.
I've read a lot about this and found solutions like Lazy<T> and and IServiceProvider, but I want to learn a clean solution for this problem and want to follow the most common suggestion to refactor the code.
We have four services in this example:
AccountService -> Login, Logout and so on
HttpService -> Do the API-Stuff
LogService -> Do some logging
LogRepository -> CRUD for the logging table / wrapper for EF
The AccountService authenticate via API using HttpService. Later, I want use the HttpService to get more data via API. HttpService now need the AccountService to get the Token for authenticate the request. This is causing a circular dependency error.
AccountService
public interface IAccountService
{
Identity Identity { get; }
Task Login(Credentials Credentials);
Task Logout();
}
public class AccountService : IAccountService
{
public Identity Identity { get; private set; }
private readonly IHttpService _httpService;
private readonly ILogService _logService;
public AccountService(
IHttpService HttpService, ILogService LogService)
{
_httpService = HttpService;
_logService = LogService;
}
public async Task Login(Credentials Credentials)
{
Identity = await _httpService.Post<Identity>(
"api/rest/v1/user/authenticate", Credentials);
}
}
HttpService
public interface IHttpService
{
Task<T> Get<T>(string uri);
Task Post(string uri, object value);
Task<T> Post<T>(string uri, object value);
}
public class HttpService : IHttpService
{
private readonly HttpClient _httpClient;
private readonly IAccountService _accountService;
private readonly ILogService _logService;
public HttpService(
HttpClient HttpClient,
IAccountService AccountService,
ILogService ILogService)
{
_httpClient = HttpClient;
_accountService = AccountService;
_logService = LogService;
}
private async Task AddAuthentication(HttpRequestMessage Request)
{
Request.Headers.Authorization = new AuthenticationHeaderValue(
"bearer", _accountService.Identity.SystemToken);
}
}
How is the best practice to solve or proper redesign this?
I've more Circular Dependency, e.g. use the LogService in LogRepository or using LogService in HttpService (because the HttpService sends Log-Entrys to the Server).
Thank you so much for your help!