简体   繁体   中英

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

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:

在此处输入图片说明

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM