MVC6从与控制器无关的类中访问DbContext



我正在开发一个ASP。Net5 MVC6网站使用EF7.

我想从一个没有从控制器调用的类访问DbContext。

有可能从那里进入吗?如果是的话,请给我一点指导,这样我就能学会怎么做了。

到目前为止,从GitHub和stackoverflow搜索了很多。关于这个话题的信息很少。

如果我需要注入到我的类,那么我应该怎么做?

    public class CarAppContext : DbContext
{
    public DbSet<Car> Cars { get; set; }
    public DbSet<BodyType> BodyTypes { get; set; }
}
public Class NotificationManager
{
    CarAppContext ctx;
    public NotificationManager(CarAppContext AppCtx)
    {
        ctx = AppCtx;
    }
    public void SendNotification(Car HisCar, UserNotification HisNotification)
    {
        //need to check he has subscribed or not
        //ctx is null here
    }
}

可以调用new CarAppContext()

但是如果你想使用依赖注入,你需要确保

  1. 你已经注册了CarAppContext和NotificationManager与依赖注入容器(通常在Startup.Configure中完成)
  2. 从依赖注入实例化NotificationManager

不奇怪你没有找到文档。ASP。. NET 5还在测试阶段,我们的文档还没有写出来。当它准备好了,会有更多的张贴在这里:http://docs.asp.net/en/latest/fundamentals/dependency-injection.html

依赖注入是"病毒式"概念,你必须在应用程序中全面使用它——通过参数/属性传递依赖,并有一个(或几个)注册根。所以答案是-将NotificationManager注册为依赖项。

甚至微软的依赖注入实现都是足够抽象的,所以你可以很容易地为每个组件注册依赖项(如Ninject模块)拥有一些类。

注意:请确保将此添加到您的文件中…

using Microsoft.Data.Entity;

最新更新