I have a class model using GRASP pattern design, specifically Controller pattern, so ProductController
handles all the Product
instances, and this handle all the Kardex
instances.
ProductController
can save, edit and delete products.
Product
can save and delete kardex movements.
Only using OOP I can handle this, but I need that some methods calls an API to save and/or get data from a DB.
My app will be constantly doing operations with this API, so I decide to use IHttpClientFactory
with DI.
If i inject controllers with their respectives interfaces is not a problem, but if a Product instance have to SaveKardex
, i will have to inject it to use HttpClientFactory
, preventing instantiate. So i did this:
public class Product
{
private readonly IHttpClientFactory _httpClientFactory;
public int prop1 { get; set; }
public Product(IHttpClientFactory httpClientFactory) //this works
{
_httpClientFactory = httpClientFactory;
}
public Product() //this also works
{
prop1 = 10;
}
public async Task<bool> SaveKardex(Kardex kardex)
{
var client = _httpClientFactory.CreateClient("BdClient");
var uriString = client.BaseAddress + $"product/kardex";
var message = RequestBuilder.RequestMessage(HttpMethod.Post, uriString);
var res = await client.SendAsync(message);
....
....
return true;
}
}
If I instanciate a new Product
or is deserialized, i could not call SaveKardex
method because i will not use the injected instance and httpClientFactory would be null.
What can i do? Any suggestions?
I thought using HttpClient instances, but is this the best way considering a lot of connections to the API?
Thanks!