ASP Module 2
Handling Data in MVC
Handling Data in MVC
  • Entity Framework Core
    • Overview
    • Setup
  • Persisting Data
    • Injecting the context
    • Saving changes
    • Entity conventions
  • Validating Data
    • Adding validation
    • Working of validation
    • Formatting data
  • Misc
    • Scaffolding Everything
Powered by GitBook
On this page
  1. Persisting Data

Injecting the context

PreviousSetupNextSaving changes

Last updated 2 years ago

Dependency injection in the controller

Open the Controllers/MoviesController.cs file and inject the context as shown

public class MoviesController : Controller
{
    //FakeContext _context;
    MvcMovieContext _context;
    public MoviesController(MvcMovieContext context) {
       // _context = new FakeContext();
       _context = context;
    } 
    //other code...
}

The constructor, with the help of Dependency Injection, receives an object of MvcMovieContext. The database context is used in each of the CRUD methods in the controller.

.NET supports the dependency injection (DI) software design pattern, which is a technique for achieving between classes and their dependencies. Dependency injection in .NET is a built-in part of the framework, along with configuration, logging, and the options pattern.

Using the same technique of dependency injection, we can inject any other service into any controller which requires it, thereby keeping the usage and implementation separate we will look at other uses of dependency injection later.

Inversion of Control (IoC)