How to Inject Dependency of ApplicationDbContext in Repository MVC6

asp.net-core-mvc asp.net-mvc entity-framework-core

Question

I'm using Asp.Net MVC 6 beta4 with Repository Pattern.

In the my Startup.cs I have someting like this:

services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<ApplicationDbContext>(options => 
                        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

//Dependency Injection
services.AddTransient<IProductRepository, ProductRepository>();

In the my Controller I can get my instance of ApplicationDbContext with:

[FromServices]
public ApplicationDbContext DbContext { get; set; }

But I cannot get the instance of ApplicationDbContext in my Repository implementation with this self segment code above.

With MVC 5 I used ServiceLocator in my Repository and took the ApplicaionDbContext so:

var context = ServiceLocator.Current.GetInstance<ApplicationDbContext>()

How to get the Instance of ApplicationDbContext in my repository with Asp.NET MVC 6?

Accepted Answer

What you probably want is to use AddScoped, and not AddTransient, so that the context will be cleand up properly when the request ends.

You also need to actually add the Context, not just the AddEntityFramework calls...

services.AddScoped<IProductRepository, ProductRepository>();
services.AddScoped<ApplicationDbContext, ApplicationDbContext>();


Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why