9

I have a Blazor Project, in the Program.cs(formaly aka Startup.cs) I added a service

            builder.Services.AddSingleton<Models.UserVisit>();
        

I can use/access that service on a razor/blazor page like this :

       @inject Models.UserVisit userVisitObj

(UserVisit is a "normal" C# .cs Class in the folder Models)

What I don't know is how can I use this "userVisitObj" in a normal C# Class that does not have a razorpage (where I would use the @inject)?

How do I use that in here (normal C# Class in the same project but without a blazor/razor-componentpage):

public class UserModel
{
    [BsonId]
    public Guid Id { get; set; }
    public CultureInfo UserCultureInfo { get; set; }
    ...

    public UserModel()
    {
        [Inject]
        Models.UserVisit userVisitObj;   // THAT DOESN'T WORK -- ERROR
    }
}

I hope I could make my question somewhat clear (please be kind I'm still a beginner).

nogood
  • 1,117
  • 1
  • 11
  • 34
  • 1
    Generally you would just follow [standard dependency injection](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#overview-of-dependency-injection). So in your case the `UserModel()` constructor would take in `Models.UserVisit` as a parameter. But how that is resolved depends on how/where you're constructing the `UserModel` class – devNull Jul 04 '20 at 16:45
  • @devNull can you elaborate on the last sentence? I find this works but it seems like magic and would like to understand it better. If I try to `new()` such a class it complains about missing parameter; but objects that are constructed by the framework seem to be able to fill in the parameter from somewhere. – M.M Jan 05 '23 at 04:09
  • @M.M same thing for me, any `new()` instancation complains about the missing parameter, did you ever figure it out? – EyeSeeSharp Feb 22 '23 at 14:17
  • @EyeSeeSharp Nope, lol – M.M Feb 22 '23 at 20:19

1 Answers1

13

You can use constructor injection as follows:

private readonly Models.UserVisit _userVisitObj
public UserModel(Models.UserVisit userVisitObj)
{
      _userVisitObj = userVisitObj;
 
}

Note that this is applicable to normal C# classes.

If your class is a component class, you need to use the Inject attribute with a public property, as for instance:

[Inject]
public Models.UserVisit UserVisit {get; set;}

Hope this helps...

enet
  • 41,195
  • 5
  • 76
  • 113
  • I have tried using the `[Inject]` version in a normal C# class (not a component class), however the property always reads as `null`, is something else needed to make it go and get the service? – M.M Jan 05 '23 at 04:01
  • in a normal class use 'constructor injection'. The first part of the answere (private field ...). – nogood Jan 05 '23 at 15:09