Daniel R
Daniel R

Reputation: 1273

Consume scoped service in Razor Model (Dependency Injection)

I want to use a scoped service in a Razor PageModel. The registration is like:

services.AddScoped<IOperationScoped, Operation>();

But Microsoft says don't use constructor injection on scoped services:

When using a scoped service in a middleware, inject the service into the Invoke or InvokeAsync method. Don't inject via constructor injection because it forces the service to behave like a singleton.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#service-lifetimes

But which option do I have to inject a scoped service in Razor outside constructor?

Upvotes: 1

Views: 515

Answers (1)

Nkosi
Nkosi

Reputation: 247008

When using a scoped service in a middleware, ...

NOTE: emphasis mine

That quote refers specifically to middleware and does not apply to PageModel, which can, and is advised to, use constructor injection.

public class MyPage: PageModel {

    //ctr
    public MyPage(IOperationScoped operation) {
        //...
    }

    //...
}

The PageModel class allows separation of the logic of a page from its presentation. It defines page handlers for requests sent to the page and the data used to render the page. This separation allows:

  • Managing of page dependencies through dependency injection.
  • Unit testing

Reference Introduction to Razor Pages in ASP.NET Core

Upvotes: 1

Related Questions