BjarkeCK
BjarkeCK

Reputation: 5729

Adding a custom singleton that is unique for each request

I've been struggling to figure out the dependency pattern that comes with asp net core. Here is what I'm trying to achieve.

_ViewImports.cshtml

...    
@inject AdminBuilder AdminBuilder
...

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddHttpContextIshSingleton<AdminBuilder>();
    ...
}

AnyCSHtmlFile.cshtml

@AdminBuilder.AddStuff()
@AdminBuilder.EnableStuff()
@AdminBuilder.DoStuff()
// It'll then populate the AdminBuilder instance, which needs to be a unique instance for each visit.

Layout.cshtml

Here I'll render the AdminBuilder at the bottom from a partial .cshtml file, based on what's been added while rendering the page.

Upvotes: 0

Views: 374

Answers (1)

Peter Hurtony
Peter Hurtony

Reputation: 470

Use services.AddScoped<AdminBuilder>().

You can read more about the built in lifetimes in the official docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1#service-lifetimes

Upvotes: 1

Related Questions