Search code examples
asp.net-coreasp.net-core-webapiasp.net-core-2.0asp.net-apicontroller

ASP.NET Core 2 WEB API - Dependency Injection


When using WEB API (only) is there a difference between API controller and normal Web Controller? I mean when adding a service like this using one of the lifetime:

  • services.AddSingleton<IService, Service();
  • services.AddScoped<IService, Service();
  • services.AddTransient<IService, Service();

will there be a difference behavior between the services in a Controller that returns a web page or a Controller that returns JSON as REST is stateless?


Solution

  • Yes, before ASP.NET Core, apps were split between ASP.NET MVC and ASP.NET Web API.

    ASP.NET Core has changed this. Now, this is one generic MVC approach (represented by MVC middleware) for dealing with requests, whether they end up returning data or views.

    Lifecycle is not affected, as the "same" pipeline implementation is executed for all requests.

    For example, you may create a controllers action defined to return dynamic response data:

        [HttpGet]
        public dynamic Index(int flag)
        {
            if (flag == 1) return new StatusCodeResult(200);
            if (flag == 2) return new { id = 1, Name = "some text" };
            else return View();
        }
    

    So depends on query parameter, it will return JSON data, only status code as a response, or View. And during controller instance creation (when some dependencies may be resolved via DI) the framework doesn't know yet what flow will be used.