I have a Blazor Project, in the Startup.cs I added a service
public void ConfigureServices(IServiceCollection services)
{
....
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).
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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.