У меня есть решение, которое имеет бизнес-сервис, бизнес-объекты, слои модели данных и проект веб-API asp.net.Я вызываю сторонний веб-API на уровне бизнес-сервисов.Я следовал по этой [ссылке] ( Используя Unity для создания синглтона, который используется в моем классе ), чтобы использовать IoC через Unity, но я получаю нулевое значение для 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
}
}