有没有一种方法可以通过Unity来实现IoC httpclient

时间:2019-07-02 14:07:31

标签: c# asp.net-web-api dependency-injection unity-container

我有一个包含业务服务,业务实体,数据模型层和asp.net Web API项目的解决方案。我在我的业务服务层中调用3rd party Web api。我遵循了此[link](Using Unity to create a singleton that is used in my Class),以便通过Unity使用IoC,但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;
        }
    }

    }

这是Unity配置:

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());
        }

添加了游戏服务。

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

        }

    }

0 个答案:

没有答案