繁体   English   中英

ASP.NET Core MVC和Entity Framework Core中的依赖项注入失败

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

我正在使用Entity Framework Core 2.1.11

我刚刚初始化了一个数据库,该数据库将在我的网站中使用。

我成功使用了Scaffold-DbContext命令,现在它已经创建了所有模型类和数据上下文类。

StartUp.ConfigureServices我具有以下内容:

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

    services.AddMvc();
}

在我看来,我需要测试以下简单内容以查看其是否正常运行:

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

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

但是不幸的是,我收到了一个隐秘的错误消息,我不确定它是什么意思:

在此处输入图片说明

要进一步补充:在调试项目时,不会破坏上下文的构造函数。 我不确定为什么

依赖注入是一种用于实现控制反转的技术,主要是将服务注入到将使用该服务的类的构造函数中。

基本上,您从其实现的接口注入服务。 例如

如果有界面

public interface IMyInterface
{
     void doMyWork();
}

然后您有一个实现此接口的服务

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

如果您正在使用MVC,则要使用DI从控制器调用此服务

public class HomeController : Controller
{
    private readonly IMyInterface _myinterface;

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

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

因此可以说您正在使用数据库连接,因为您的启动配置需要绑定服务和接口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()
}

有关用于ASP.NET Core的DI的更多信息,请参阅docs

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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