MVC6 Access DbContext From Classes Not Related To Controller

asp.net-core-mvc entity-framework-core

Question

I am developing a ASP.Net5 MVC6 website Using EF7.

I wanted to access DbContext from one of my classes which is not being called from Controller.

Is it possible to access from there? If yes then please guide me a little so that I can learn how to do it.

So far searched a lot from GitHub and stackoverflow. Very little information on this topic.

If i need to inject to my class then how should I do it?

    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
    }
}

Popular Answer

You could call new CarAppContext().

But if you want to use Dependency Injection instead, you will need to make sure that

  1. You have registered both CarAppContext and NotificationManager with the dependency injection container (generally done in Startup.Configure)
  2. Instantiate NotificationManager from dependency injection

Not surprised you haven't found docs. As ASP.NET 5 is still in beta, our docs haven't been written yet. When its ready, there will be more posted here: http://docs.asp.net/en/latest/fundamentals/dependency-injection.html



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why