2

I'm using ASP.NET Core MVC and Web API and trying to consume the internal Web API (done using ApiController, prepare for future cross-platform application use), I saw an answer which doesn't need to use HttpClient or any Http Request features to get data from Web API, refer: Consuming web api controller action from mvc controller

I'm trying to do the similar thing, but my auto generated Web API Controller comes with DBContext parameter, which causing me unable to follow what is mentioned from the link.

Below is what i have in my Controller which caused me unable to follow actions mentioned in the link above:

    private readonly MyTestDBContext _context;

    public MfgProductsController(MyTestDBContext context)
    {
        _context = context;
    }

If the "MyTestDBContext context" parameter supposed to remain, what should I write in my Controller in order to pass the DBContext in?

Or if there's a way to remove "MyTestDBContext context" from the parameter, how the constructor supposed to change to?

3
  • mxmissile's answer will work, but I think it'd make more sense to refactor the code you're calling into a service that both your MVC and Web API controllers depend on, and call that instead rather than going through the controller. Depending on a controller feels wrong. Commented Aug 6, 2019 at 14:17
  • @Rup is 100% correct Commented Aug 6, 2019 at 14:18
  • @Rup Is there any example for what you have mentioned? Sorry I'm new to this. I tried mxmissile's suggestion but I get another error. InvalidOperationException: Unable to resolve service for type 'WebApplication4.Controllers.MfgProductsController' while attempting to activate Commented Aug 7, 2019 at 0:17

1 Answer 1

2

Let the container do its job, just add the controller as a dependency in your controller:

public class MyController : Controller
{
    public MyController(MfgProductsController productsController) 
    {
        _productsController = productsController;
    }

    private readonly MfgProductsController _productsController;    
}

It should fill all dependencies for you.

Sign up to request clarification or add additional context in comments.

Comments

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.