0

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.

BjarkeCK
  • 5,694
  • 5
  • 41
  • 59
  • Perhaps View components can help you: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.1 –  Sep 29 '18 at 17:06
  • 1
    What is exactly the problem with the "scoped" scope? It resolves only once every http request, so it is singleton in the scope of the http request. – Peter Hurtony Sep 29 '18 at 17:15
  • @PeterHurtony Nothing, nothing at all! Scoped was exactly what I was looking for! You're welcome to add an answer with that. Thanks a lot. The API documentation for all of them says the same. "Adds a scoped services of the type specified in the serviceType to the specified IServiceCollectrion". So it's a bit hard figured out what it is you actually need. Any article or documentation, in particular, you would recommend reading up on? – BjarkeCK Sep 29 '18 at 18:02
  • 1
    Possible duplicate of [What is the difference between services.AddTransient, service.AddScoped and service.AddSingleton methods in ASP.NET Core?](https://stackoverflow.com/questions/38138100/what-is-the-difference-between-services-addtransient-service-addscoped-and-serv) – Kirk Larkin Sep 29 '18 at 18:33

1 Answers1

1

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

Peter Hurtony
  • 472
  • 3
  • 17