prog1011
prog1011

Reputation: 3495

How to create Application variable in .Net Core 2.0?

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.

Upvotes: 3

Views: 1688

Answers (2)

Neville Nazerane
Neville Nazerane

Reputation: 7019

Understand the reasoning behind not wanting to inject, you can still use a singleton and access the value from HttpContext using this:

HttpContext.RequestServices.GetService<ApplicationLevelData>();

To use this function you will have to import Microsoft.Extensions.DependencyInjection.

You can also create an extension function for this if you like:

public static class HttpContextExtensions {
    public static ApplicationLevelData GetAppData(this HttpContext HttpContext)
        => HttpContext.RequestServices.GetService<ApplicationLevelData>();
}

You can now get your ApplicationLevelData within any controller by using HttpContext.GetAppData().

Upvotes: 1

Guilherme
Guilherme

Reputation: 5341

public static class Globals
{
    public static Guid TestProperty { get; set; }
}

Usage (in any place):

var guid = Globals.TestProperty;

You said:

this data will comes from database (only once)

You can also create as private set, like this:

public static Guid TestProperty { get; private set; }

Then it is only possible to set the value inside the class Globals, making this sort of a readonly property.

Also, please see this answer about the constructor. It is a bit different on a static class.

Upvotes: 0

Related Questions