Using Entity Framework DbContext with Dependency Injection

In this article, I would explain how you can do Database Dependency Injection of Entity Framework Core in .NET Core or .NET 5.

According to Wikipedia: In software engineering, dependency injection is a technique in which an object receives other objects that it depends on, called dependencies. Typically, the receiving object is called a client and the passed-in (‘injected’) object is called a service. The code that passes the service to the client is called the injector. Instead of the client specifying which service it will use, the injector tells the client what service to use. The ‘injection’ refers to the passing of a dependency (a service) into the client that uses it.

I’ll dive into the technical directly. In .NET Core and .NET 5, we have a file called Startup.cs. In the file there is a method ConfigureServices which looks like this:

public void ConfigureServices(IServiceCollection services)
{
     //Code
}

Assuming that you have your Database context named as MyDatabaseContext then

services
   .AddDbContext<MyDatabaseContext>(c =>
          c.UseSqlServer(Configuration
	  .GetConnectionString("MyDatabaseContext")
   )
);

Your project should have a file called appsettings.json. In that file, add the connection string of your Database like the below example:

"ConnectionStrings": {
    "MyDatabaseContext": "Server=XXXXXX;Initial Catalog=MyDb; User Id=sa; Password=XXXX",
}

Keep in mind that the connection string name in appsettings.json and in the ConfigureServices method should match.

Once the database is set, then in your Controllers or Service classes, you can get reference to your database context using the following example.

You will be declaring a variable of your database context in your desired Controller or Service class:

private readonly MyDatabaseContext _db;

In the constructor of the class, add MyDatabaseContext as a parameter and assign the value to the declare variable _db. If the Controller class is called UserRegistrationController, then the constructor would look like

public UserRegistrationController(MyDatabaseContext db)
{
    _db = db; //Assigning the passed value to the defined variable
}

The database can then further be used inside any of the methods of that controller like:

[HttpPost("Register")]
public ActionResult Register(UserRegister request)
{
    //Your business logic
    _db.User.Add(request);
    _db.SaveChanges();
}

So the resulting Controller will look like

[ApiController]
public class UserRegistrationController : ControllerBase
{
    private readonly MyDatabaseContext _db;
    public UserRegistrationController(MyDatabaseContext db)
    {
        _db = db;
    }

    [HttpPost("Register")]
    public ActionResult Register(UserRegister request)
    {
        //Your business logic
        _db.User.Add(request);
        _db.SaveChanges();
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s