Reputation: 1574
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?
Upvotes: 6
Views: 4494
Reputation: 93424
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>();
Upvotes: 5