NMNamuAgain
NMNamuAgain

Reputation: 59

Two Constructors in Controller in .NET

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

Answers (2)

G. Belkin
G. Belkin

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

Robert P
Robert P

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

Related Questions