Dependency Injection failing in ASP.NET Core MVC and Entity Framework Core

asp.net-core-mvc c# entity-framework-core razor

Question

I am using Entity Framework Core 2.1.11

I have just initialized a database I will be using in my Website.

I used the Scaffold-DbContext command successfully, and it has now created all the model classes and data context class.

In the StartUp.ConfigureServices I have the following:

public void ConfigureServices(IServiceCollection services)
{
    string connection = //correct connection string used in Scaffolding
    services.AddDbContext<Models.WebsiteContext>(options => options.UseSqlServer(connection));

    services.AddMvc();
}

In my view, I have the following simple thing to test to see if it is working correctly:

@page
@model IEnumerable<Website.Models.Levels>

<table>
  @foreach (var item in Model)
  {
    <tr>
      <td>@item.Id</td>
    </tr>
  }
</table>

But unfortunately I get a cryptic error message that I'm not sure what it means:

enter image description here

To further add: when I debug the project, the constructor of the context does not get hit. I'm not sure why

1
0
7/14/2019 5:20:40 AM

Accepted Answer

Dependency injection is a technique for achieving inversion of control it is majorly to inject a service into the constructor of the class where it will be used.

Basically, you inject a service from an interface it implements. for instance

If you have an interface

public interface IMyInterface
{
     void doMyWork();
}

And then you had a service that implements this interface

public class MyService : IMyInterface
{    
    public void doMyWork() {
        //the work is done here
        //get to the db and fetch some good stuff the users needs
    } 
}

An you want to use DI to call this service from your controller if you are using MVC

public class HomeController : Controller
{
    private readonly IMyInterface _myinterface;

    public HomeController(IMyInterface myinterface)
    {
        _myinterface = myinterface;
    }

    public IActionResult Index()
    {
         var theWork = _myinterface.doMyWork();
    }
}

So lets say you are using a db connection as in your case your startup config needs to bind the service and the interface services.AddSingleton

public void ConfigureServices(IServiceCollection services)
{
    string connection = //correct connection string used in Scaffolding
    services.AddDbContext<Models.WebsiteContext>(options => options.UseSqlServer(connection));

    services.AddSingleton<IMyInterface, MyService>();

    services.AddMvc()
}

for more on DI for ASP.NET Core see docs

1
7/14/2019 5:08:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow