Olga
Olga

Reputation: 1455

Why is DbContext (ASP.NET) null in MyService?

I use c#, ASP.NET Core, EF.

I have Startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            ...
        }

I have Controller:

public class HomeController : Controller
{
        public AppDbContext _db;

        public HomeController(AppDbContext db)
        {
            _db = db;
        }

        public IActionResult Index()
        {
         // _db is NOT NULL           
         var d = _db.Users.FirstOrDefault();
        }
}

I have class MyService.cs:

public class MyService
{
        public static AppDbContext _db;

        public MyService(AppDbContext db)
        {
            _db = db;
        }

        public static void GetOtherValue()
        {   
             // _db is NULL           
             var d = _db.Users.FirstOrDefault();
        }
  }

HomeController works correctly: _db is not null.

Why variable _db is null in MyService.cs? How to fix it?

UP:

public class OtherController : Controller
{
    ....
    MyService.GetOtherValue();
    ....
}

Upvotes: 3

Views: 2975

Answers (1)

miechooy
miechooy

Reputation: 3422

You are not injecting your service anywhere.

You just use static method thus constructor is never called. You can inject through the constructor.

First add a service into ASP.Net Core container:

services.AddScoped<MyService, MyService>();

Then inject via constructor in your controller class:

public class HomeController : Controller
{
    private readonly MyService _myService;

    public HomeController (MyService myService)
    {
        _myService = myService;
    }
}

MyService class will be created every requests ( AddScoped()). Then the your DbContext will be created automatically.

Read more about DI in .NET Core

Upvotes: 5

Related Questions