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?
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.
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.
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.
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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With