0

I have a solution which has business service, business entities, data model layers, and an asp.net web API project. I am calling 3rd party web api in my business service layer. I followed this [link] (Using Unity to create a singleton that is used in my Class) in order to use IoC via Unity but I am getting null for httpclient.

public class Utilities : IUtilities
    {
        private static HttpClient _httpClient;

        public Utilities(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }


        public static async Task<HttpResponseMessage> CallRazer(GameRequest gameRequest, string url)
        {

            //Convert request
            var keyValues = gameRequest.ToKeyValue();
            var content = new FormUrlEncodedContent(keyValues);

            //Call Game Sultan
            var response = await _httpClient.PostAsync("https://test.com/"+url, content);
            return response;
        }
    }

    }

Here is Unity config:

public static void RegisterTypes(IUnityContainer container)
        {
            // NOTE: To load from web.config uncomment the line below.
            // Make sure to add a Unity.Configuration to the using statements.
            // container.LoadConfiguration();

            // TODO: Register your type's mappings here.
            // container.RegisterType<IProductRepository, ProductRepository>();
            container.RegisterType<IGameServices, GameServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());
            container.RegisterType<IUtilities, Utilities>(new ContainerControlledLifetimeManager());
            container.RegisterType<HttpClient, HttpClient>(new ContainerControlledLifetimeManager(), new InjectionConstructor());
        }

Game Service added.

public class GameServices : IGameServices
    {
        private readonly UnitOfWork _unitOfWork;

        /// <summary>
        /// Public constructor.
        /// </summary>
        public GameServices(UnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="requestDto"></param>
        /// <returns></returns>
        public async Task<HttpResponseMessage> GamePurchase(RequestDto requestDto)
        {
            try
            {
                string htmlResponse = null;
                HttpResponseMessage response = null;
                using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    //Transform DTO into GameRequest for calling Razer Initiate
                    var config = new MapperConfiguration(cfg => { cfg.CreateMap<RequestDto, GameRequest>(); });
                    var iMapper = config.CreateMapper();
                    var gameRequest = iMapper.Map<RequestDto, GameRequest>(requestDto);
                    //Create signature
                    gameRequest = Utilities.CreateSignature(gameRequest, RequestType.Initiate);
                    //Unique reference ID
                    gameRequest.referenceId = Guid.NewGuid().ToString();

                    //Add request into database
                    _unitOfWork.GameRepository.Insert(gameRequest);

                    #region Call Razer initiate/confirm
                    response = await Utilities.CallRazer(gameRequest, "purchaseinitiation");

                    //Read response
                    htmlResponse = await response.Content.ReadAsStringAsync();
                    var gameResponse = JsonConvert.DeserializeObject<GameResponse>(htmlResponse);
                    //Adding response into database
                    _unitOfWork.GameResponseRepository.Insert(gameResponse);
                    if (gameResponse.initiationResultCode == "00")
                    {
                        //Create signature
                        var gameConfirmRequest = Utilities.CreateSignature(gameRequest, RequestType.Confirm);


                    }

                    #endregion

                    await _unitOfWork.SaveAsync();
                    scope.Complete();

                }

                return response;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

        }


        public enum RequestType
        {
            Initiate = 0,
            Confirm = 1

        }

    }
14
  • Are you getting to all posted code and are you getting any exceptions? You did not post the code that is calling the Utilities method that is passing the httpClient so I can't tell why it is null. Commented Jul 2, 2019 at 14:18
  • @jdweng I added the Game Service code which calls Utilities. Commented Jul 2, 2019 at 14:24
  • Where is "new Utilities(client)"? Commented Jul 2, 2019 at 14:37
  • @jdweng I don't get what you mean? Would you please explain? Commented Jul 2, 2019 at 14:39
  • you need to instantiate the client before injecting, nodogmablog.bryanhogan.net/2017/10/… Commented Jul 2, 2019 at 14:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.