leSyndrome
leSyndrome

Reputation: 23

Dependency Injection outside a constructor in Server-side Blazor

I want to use a scoped service in a method of a singleton service in server-side Blazor. I found out that you can use the [FromServices] Attribute in the function parameters, but when I call the method I get a compiler error for calling the method with less parameters. I tried calling the method with a dummy parameter in the hope it would get overwritten when called, but that was not the case.

Scoped Service:

public class UserContext
{
    public string SomeUserRelatedData {get; set;}
}

Singleton service:

public class GlobalService
{
    ...
    public void DoSomethingWithUserData([FromServices]UserContext usercontext)
    {
        ...
    }
}

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton<GlobalService>();
        services.AddScoped<UserContext>();
    }
}

Upvotes: 0

Views: 639

Answers (1)

Sadly you can't do that.

You can use this [FromServices] only in the method that is called by the framework. In this case in any action from a controller or in Invoke method in middleware.

But there is a solution to your problem. I assume that the method that calls DoSomethingWithUserData is scope. In that class ( or method if it's an endpoint ) you can inject your UserContext and call the method from GlobalService with that instance.

Upvotes: 1

Related Questions