In this recipe, we will learn in a simple way how to register, resolve, and give a life cycle to an abstraction in ASP.NET Core.
Dependency injection is now native in ASP.NET Core.
Importing Microsoft.Extensions.DependencyInjection
in project.json
(formerly web.config
), and by a using statement in Startup.cs
(formerly global.asax
), we can use this internal component to manage DI for our application, represented by the IServiceProvider
interface.
We will inject the ServiceProducts
class by using a constructor in the HomeController
of an ASP.NET MVC 6 application:
- First, we create a class called
Product
:
- We then create an interface called
IProductService:
- Next, we create a class called
ProductService
:
- Let's use
ProductService
in ourHomeController
, creating an instance ofProductService
by injecting theProductService
abstraction in theHomeController
constructor.ProductService
will be available for the wholeHomeController...