paint-brush
ASP.NET Core — How to use Dependency Injection in Entity Framework Coreby@yogihosting
126,586 reads
126,586 reads

ASP.NET Core — How to use Dependency Injection in Entity Framework Core

by YogiJanuary 4th, 2019
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

<strong>ASP.NET Core</strong> has an excellent <strong>Dependency Injection</strong> feature through which this framework provides you with an object of any class that you want. So you don’t have to manually create the class object in your code.

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - ASP.NET Core — How to use Dependency Injection in Entity Framework Core
Yogi HackerNoon profile picture

Dependency Injection with Entity Framework Core

ASP.NET Core has an excellent Dependency Injection feature through which this framework provides you with an object of any class that you want. So you don’t have to manually create the class object in your code.

In this tutorial I will teach you how to use the Dependency Injection method in Entity Framework Core. This will provide you can get the following benefits:

1. The object of ‘DbContext’ class through Dependency Injection.

2. Fetch the connection string from ‘appsettings.json’ instead of from ‘OnConfiguring()’ method of ‘DbContext’ class.

Connection String inside OnConfiguring() method

Normally you provide your database connection string in OnConfiguring() method of DbContext class like this:





protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){if (!optionsBuilder.IsConfigured){optionsBuilder.UseSqlServer(@"Server=Smile;Database=Shop;Trusted_Connection=True;");

}  

}

This approach is not nice since it is better to store the connection string in appsettings.json file. After applying the Dependency Injection in Entity Framework Core you can simply remove everything inside the OnConfiguring() method like this:






protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){if (!optionsBuilder.IsConfigured){}}

You need to do the following 3 changes as described below:

1. Create appsettings.json file to store the Database Connection String

The code for appsettings.json file storing the Database Connection String value is given below:





{"ConnectionStrings": {"DefaultConnection": "Server=Smile;Database=Shop;Trusted_Connection=True;"}}

2. Create appsettings.json file to store the Database Connection String

In your DbContext class go and add the constructor that inherits the base class. Also remove the connection string from OnConfiguring() method. The code of the DbContex class should be:




public class ShopContext : DbContext{public ShopContext(DbContextOptions<ShopContext> options) : base(options) { }public DbSet<Products> Products { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
{  
}

protected override void OnModelCreating(ModelBuilder modelBuilder)  
{  
}  

}

3. Add DbContext class as a service in Startup.cs class

Change the Startup.cs class to get the IConfiguration object of Microsoft.Extensions.Configuration namespace in it’s Constructor.

Inside the constructor set the value of a public property of type IConfiguration with the value of IConfiguration object given in it’s parameter.

The code for this is:




public Startup(IConfiguration configuration){Configuration = configuration;}

public IConfiguration Configuration { get; }

This change will help you to read the appsettings.json file in the Startup.cs class.

Next, add the DbContext class as a service inside the ConfigureService() method. See the below code:

services.AddDbContext<ShopContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

The updated code of the Startup class should be:






public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddDbContext<ShopContext>(options => options.UseSqlServer(Configuration\["ConnectionStrings:DefaultConnection"\]));  
    services.AddMvc();  
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
{  
    app.UseStaticFiles();  
    app.UseDeveloperExceptionPage();  
    app.UseMvc(routes =>  
    {  
        routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
    });  
}  

}

Get DbContext object in Controller using Dependency Injection

Now you are ready and let me show how to get the DbContext class object in the Constructor using Dependency Injection. All you have to do is to add the DbContext class object in the constructor of the Controller, and set a public property value to it.

You can learn all about Dependency Injection feature from this tutorial — Dependency Injection in ASP.NET Core

You add the below code to the Constructor:

private ShopContext shopContext;




public HomeController(ShopContext sc){shopContext = sc;}

Now you are ready to use Entity Framework Core to communicate with the database.

To Read Records from the database:

shopContext.Teacher;

To Create records in the database:


shopContext.Products.Add(product);shopContext.SaveChanges();

See the updated code of the Controller which also lists the action methods that reads and inserts records.







public class HomeController : Controller{private ShopContext shopContext;public HomeController(ShopContext sc){shopContext = sc;}

public IActionResult Index()  
{  
    return View(shopContext.Teacher);  
}

public IActionResult Create()  
{  
    return View();  
}

\[HttpPost\]  
public IActionResult Create\_Post(Products product)  
{  
    if (ModelState.IsValid)  
    {      
        shopContext.Products.Add(product);  
        shopContext.SaveChanges();  
        return RedirectToAction("Index");  
    }  
    else   
        return View();  
}  

}

Conclusion

I hope you like this tutorial on Entity Framework Core with Dependency Injection. It is just one step to improve your code. If you like this tutorial then please give me some claps, and do follow me for 1 tutorial on Web Development every week.

Also check my other article in HACKERNOON — 7 Common Web Development problems which every developer from Beginners to Experts should know [with multiple solutions]