mardi 1 janvier 2019

Need suggestions in help making a conditional parameter initialize a class with DI, C#, and Web API 2.0

I am using Unity dependency injection and Web API 2.0.

I have a controller which i am injecting my unit of work:

public ProductController(IUnitOfWork unitOfWork)
{
    _unitOfWork = unitOfWork;
}

I then have a method in that controller:

public HttpResponseMessage UpdateProducts(string website)
{ 
   ProductAPI productAPI;
   Enum.TryParse(website, out Website website);

   productAPI = new ProductAPI(_unitOfWork, website);
   productAPI.UpdateProducts();
}

The method takes in a parameter website which is a enum. It has 3 different values (website1, website2, website3).

This is the ProductAPI constructor that takes in UOW and the website enum:

public ProductAPI(IUnitOfWork unitOfWork, Website website)
{
    _unitOfWork = unitOfWork;
    _website = website;
    _httpClient = CommonAPI.GetHttpClient(website);
}

The CommonAPI class is a static class that returns the httpclient based on the website.

public static HttpClient GetHttpClient(Website website)
{
    HttpClient httpClient = new HttpClient();

    if (website == Website.1)
    {
        //return httpclient for website 1
    }
    else if (website == Website.2)
    {
        //return httpclient for website 2
    }
    else if (website == Website.3)
    {
        //return httpclient for website 3
    }

    return httpClient;
}

The ProductAPI class also has calls within its methods that use the UOW but also use the website enum to filter based on the website value:

List<ProductViewModel> products = _unitOfWork.ProductRepository.GetProducts(_website.ToString());

Is there a better and cleaner way to set this code up based on that website enum?




Aucun commentaire:

Enregistrer un commentaire