HappyCoding HappyCoding - 2 months ago 7
ASP.NET (C#) Question

Understanding about constructor in Web Api

My web api looks like:

[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly ApplicationDbContext _context;

public ValuesController(ApplicationDbContext context)
{
_context = context;
}

[HttpGet]
public string Get()
{
// get random user

var user = _context.Users.SingleOrDefault();

return user?.Email ?? "";
}
}


Trying to call it via jquery:

$.get('/api/values', function (email) {
console.log(email)
})


I've 2 questions:

1/. Why didn't
console.log(email)
work although I was getting the response successful?

1

There was nothing in the
Console
tab.

2/. When I made a request to server (
/api/values
), the breakpoint had been caught:

2

My question: where had
ValuesController
been called within
context
? I'd sent a request from client, then the constructor was hit (I'm sure that I didn't send something like
ApplicationDbContext
from client to server :v)

UPDATE: By changing
$.get('/api/values', {}, function (email) {}
to
$.get('/api/values', function (email) {}
. I've fixed the first problem. It's my bad. Sorry about that.

Answer

Shorter Answer

My question: where had ValuesController been called within context? I'd sent a request from client, then the constructor was hit.

The HTTP Request arrived. ASP.NET MVC Routing told the application to use the ValuesController to handle the request. The application constructed the ValuesController, supplying an instance of ApplicationDbContext via dependency injection.

Longer Answer

The Startup.Configure method is used to specify how the ASP.NET application will respond to individual HTTP requests. Since you are using Web API, you have configured app.UseMvc(). Result: when an HTTP Request arrives, MVC Routing tells the application to use the appropriate controller.

The Startup.ConfigureServices method is used to specify services that are available via dependency injection. Since you are injecting an ApplicationDbContext into your constructor, you have configured services.AddDbContext<ApplicationDbContext>(). Result: when the application constructs a ValuesController, ASP.NET Dependency Injection will provide an instance of the ApplicationDbContext.

Comments