Reputation: 59
How do I use two constructors in my Controller in my Controller?
I have these two controllers in my public class OrdersController
and I need them both for CRUD operations both by context and with HttpClientFactory for another API
private readonly IHttpClientFactory httpClientFactory;
// I want to use this constructor as well as
[ActivatorUtilitiesConstructor]
public OrdersController(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
private readonly AnimimoMicroservicesNewOrderServiceContext _context;
// this one
public OrdersController(AnimimoMicroservicesNewOrderServiceContext context)
{
_context = context;
}
Thanks in advance for any help
Upvotes: 1
Views: 411
Reputation: 56
You can use Robert's solution, or on the other hand you can inject some objects directly into contoller's method using FromServicesAttribute when in necessary.
Example:
private readonly IHttpClientFactory httpClientFactory;
public OrdersController(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
[HttpPost]
public IActionResult CreateOrder([FromServices] AnimimoMicroservicesNewOrderServiceContext context)
{
var data = context.CallMethod();
return Ok(data);
}
Upvotes: 2
Reputation: 15968
Might you be looking for a constructor that takes two arguments?
public OrdersController(IHttpClientFactory httpClientFactory, AnimimoMicroservicesNewOrderServiceContext context)
{
_context = context;
this.httpClientFactory = httpClientFactory;
}
Upvotes: 2