Search code examples
asp.net-coredependency-injectionrazor-pages

Can't use injected class in Razor Pages code-behind class


I have a simple page which just shows the list of movies. I injected DbContext into my page:

List.cshtml

@inject MovieContext Db

and try to use it in code-behind class:

List.cshtml.cs

public class ListModel : PageModel
{
    public IList<Movie> Movies { get; set; }

    public async Task OnGetAsync()
    {
        Movies = await Db.Movies.ToListAsync();
    }
}

However, I get the error:

The name 'Db' does not exist in the current context

I have also tried to inject the context with [Inject] attribute, but this didn't work either:

public class ListModel : PageModel
{
    public IList<Movie> Movies { get; set; }

    // Inject context
    [Inject] public MovieContext Db { get;set; }

    public async Task OnGetAsync()
    {
        Movies = await Db.Movies.ToListAsync();
    }
}

I get the following error:

NullReferenceException: Object reference not set to an instance of an object.


Solution

  • You only need to use dependency injection directly in the code-behind class, as shown below.

    public class ListModel : PageModel
        {
            private readonly MovieContext _context;
            public ListModel(MovieContext context)
            {
                _context = context;
            }
            public IList<Movie> Movies { get; set; }
    
            public async Task OnGetAsync()
            {
                Movies = await _context.Movies.ToListAsync();
            }
        }
    

    For more details,you can see the doc.