I have created website using .Net Core 2.0. Now I want to store some values which are not user specific, I want to make those value shareable across all the users which are logged in. So for that I can use Application Variable. But in .Net Core 2.0 there is no built in way to achieve this.
What I have tried
I have created one class as below.
public class ApplicationLevelData
{
public Guid TestProperty { get; set; }
public ApplicationLevelData()
{
TestProperty = Guid.NewGuid(); // this data will comes from database (only once)
}
}
After that under Startup.cs file under ConfigureServices method I have wrote below line.
services.AddSingleton<ApplicationLevelData>();
And in each Controller I need to inject that service as below.
private ApplicationLevelData _appData;
public HomeController(ApplicationLevelData appData)
{
_appData = appData;
}
And after that we can user that in entire Controller.
But, I don't want this Inject thing. Can we make application data available using HttpContext?
Can anyone suggest me the way that how can I create Application variable in .Net Core 2.0?
Any help would be highly appreciated.
Thanks.
HttpContexthere.HttpContexthere.HttpContextis better. BecauseHttpContextis by default available in all controllersHttpContextat all, so why include it there? If you basically want a singleton and don't want the testing and isolation benefits of dependency injection, use the singleton pattern. I wouldn't personally do that myself - I'd use dependency injection to make it clear where you need it, and to enable easy testing - but it's certainly feasible, and makes more sense IMO than usingHttpContextfor something which is unrelated to the actual request.