Mavershang
Mavershang

Reputation: 1278

How to avoid reload resource in ASP.NET core controller

I am new to ASP.net core. Having a web API connect to database using EntityFramework core. The controller take request, do some analysis, and send the response as below

public class CentoDataController : ControllerBase
{
    private readonly CentoWebDBContext _context;
    private HPOSubSimHolder _hpoSubSimHolder;

    public CentoDataController(CentoWebDBContext context)
    {
        _context = context;            
        _hpoSubSimHolder = new HPOSubSimHolder(hpofile);
    }

    [HttpGet("{id}")]
    public ActionResult<CentoData> GetCentoData(string id)
    {
        IQueryable<CentoData> r = AnalysisMethod(id, _hpoSubSimHolder);
        return r;
    }

The code works, but _hpoSubSimHolder will be reloaded once a new request comes in. I guess I shouldn't share controller between requests. But how can I avoid reloading _hpoSubSimHolder ?

Upvotes: 0

Views: 437

Answers (2)

Duck Ling
Duck Ling

Reputation: 2160

I can see that you're using .net core dependency injection

If you want that service to be shared across requests, think of making it a Singleton.

You can choose between AddScoped, AddTransient and AddSingleton when registering dependencies.

In your startup.cs class:

public void ConfigureServices(IServiceCollection services)
{

    // some code 
    services.AddSingleton<HPOSubSimHolder>(new HPOSubSimHolder());

}

Singleton means only a single instance will ever be created. That instance is shared between all components that require it. The same instance is thus used always.

Scoped means an instance is created once per scope. A scope is created on every request to the application, thus any components registered as Scoped will be created once per request.

Transient The services created using transient lifetime will be created each time they are requested. This lifetime works best for lightweight services. (Source)

Upvotes: 1

MichaC
MichaC

Reputation: 13410

Controllers are always instantiated per request. To control lifetime of any resources or dependencies the controller should use, you can use the build in Dependency Injection (DI).

Most examples setup DI in your startup.cs ConfigureServices method. The DI container allows 3 different lifetime states, in your case I guess you can try to add the HPOSubSimHolder as singleton.

I have no idea what HPOSubSimHolder is and what the implementation details are, hence its hard to tell if that'll work for you. But it would be the "normal" way of setting this up ;)

Upvotes: 0

Related Questions