Home > Software engineering >  How can I avoid resolving a service when not needed?
How can I avoid resolving a service when not needed?

Time:10-25

I have a Razor page that uses a service for a maintenance job that runs once a week, like this:

public class IndexModel : PageModel
{
    public IndexModel(IMyService service)
    {
        myService = service;
    }

    private IMyService myService;;

    public void OnGet()
    {
        if (DateTime.Now - LastCheck > TimeSpan.FromDays(7))
        {
            IMyService useService = myService; // Use the service
        }
    }
}

However, as I have understood, the service is resolved on each request, even though it's only needed once a week.

This costs time and memory.

Is there a way to only resolve the service when it is used?

How can

CodePudding user response:

One option could be to register it as a Func<MyService> so that you can lazy instantiate e.g. registration:

services.AddSingleton<Func<MyService>>(_ => () =>
    return (DateTime.Now > TimeSpan.FromDays(7)) ? new MyService() : null);

then

public class IndexModel : PageModel
{
    public IndexModel(Func<MyService> func)
    {
        myService = func.Invoke();
    }

    private IMyService myService;

    public void OnGet()
    {
        myService?.DoSomething();
    }
}

Another option could be to register it as a singleton e.g.

services.AddSingleton<IMyService, MyService>();

CodePudding user response:

you can register it as singleton, then it will be just one item of it

the resolving is not important (it won't create a new one every time , it would just gets it form some sort of dictionary)

take a look at this Microsoft article : https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0

  • Related