Search code examples
asp.net-coredependency-injectionasp.net-core-mvc

IwebHostEnvironment interface


I have used IwebHostEnvironment in my code. IWebHostEnvironment is an interface used to provide info about hosting & can get data about path from it

Why can I take an instance from it and inject it like I was injecting a _db without registering it in ConfigureServices method like I register a Db context?

public class ProductController : Controller
{
    private readonly App_DbContext _db;
    private readonly IWebHostEnvironment _webHostEnvironment;
    public ProductController(App_DbContext db,IWebHostEnvironment webHostEnvironment)
    {
        _db = db;
        _webHostEnvironment = webHostEnvironment;
    }
    public IActionResult Index()
    {
        IEnumerable<Product> products= _db.Product;
        return View(products);
    }
}

this is configure services Method

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<App_DbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddControllersWithViews();
}

Solution

  • Agree with @Nkosi, you can refer to this section, IWebHostEnvironment is one of the framework-registered services.

    enter image description here