Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inject Dependency of ApplicationDbContext in Repository MVC6

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?

like image 226
Renatto Machado Avatar asked Jul 09 '15 17:07

Renatto Machado


People also ask

How do we implement dependency injection?

Dependency Injection is done by supplying the DEPENDENCY through the class's constructor when creating the instance of that class. The injected component can be used anywhere within the class. Recommended to use when the injected dependency, you are using across the class methods.

Can we inject dependency in Viewcomponent?

A view component class: Supports constructor dependency injection. Doesn't take part in the controller lifecycle, therefore filters can't be used in a view component.

What is dependency injection with example?

Dependency injection (DI) is a technique widely used in programming and well suited to Android development. By following the principles of DI, you lay the groundwork for good app architecture. Implementing dependency injection provides you with the following advantages: Reusability of code.

How can dependency injection be resolved?

Resolve dependencies using IServiceProvider You can use the IServiceCollection interface to create a dependency injection container. Once the container has been created, the IServiceCollection instance is composed into an IServiceProvider instance. You can use this instance to resolve services.


1 Answers

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>();
like image 186
Erik Funkenbusch Avatar answered Sep 19 '22 02:09

Erik Funkenbusch