How would I go about setting global variables in ASP.NET Core 6.0(razor pages)?
I have some information in the database, for example, ServiceName, ContactEmail and so on, and want to save it to my static class.
I don't want to access the database every time I need to display the information.
In addition, there aren't Global.asax in ASP.NET Core .
In ASP.NET MVC 5 (based on .net framework), I could do it like
// global.asax
protected void Application_Start() {
var context = new DefaultConnection();
MyConfig.ServiceName = context.GlobalSettings.SingleOrDefault().ServiceName;
// MyConfig is my static class
}
But I don't know where I should do it in ASP.NET Core project.
How can I do that? Please help me.
So lazy-loading is probably a very good choice for you.
Step 1: Create a data service that provides your data.
public interface IStaticDbData // Think of a better name!
{
public Task<string> GetContactEmailAsync();
public Task<string> GetServiceNameAsync();
// Etc.
}
public class StaticDbData : IStaticDbData
{
// Since we want a singleton, we'll have to synchronize the data fetching.
private object _lock = new object();
private string _contactEmail;
private string _serviceName;
// Etc.
// Try to create a single function that loads all of the data in one round trip to the DB.
// This will run in its own thread, so the calling thread can be awaited.
private Task LoadAllDataAsync()
=> Task.Run(() =>
{
lock (_lock)
{
//Re-check after locking.
if (_contactEmail != null)
{
return;
}
// Database code here to extract your data.
// Save to the individual fields.
}
});
public async Task<string> GetContactEmailAsync()
{
// See if data is there.
if (_contactEmail != null)
{
return _contactEmail;
}
// Data was not there. Load data.
await LoadAllDataAsync();
return _contactEmail;
}
public async Task<string> GetServiceNameAsync()
{
if (_serviceName != null)
{
return _serviceName;
}
await LoadAllDataAsync();
return _serviceName;
}
}
Step 2: Now that you have your service interface and service implementation, register the m in the IoC container. In program.cs:
builder.Services.AddSingleton<IStaticDbData, StaticDbData>();
Step 3: Consume the service as you would any other service.
public class SomeOtherServiceOrControllerOrWhatever
{
private IStaticDbData StaticDbDataSvc { get; }
// Constructor-injected.
public SomeOtherServiceOrControllerOrWhatever(IStaticDbData staticDbDataSvc)
{
StaticDbDataSvc = staticDbDataSvc;
}
}
NOTE: Make sure that your consuming services are also registered and resolved using the IoC container.
This is sudo code
You can create a static class with static properties:
public static class MyConfig
{
public static string Setting1 {set; get;}
...
}
then write a method to fetch data from your database and fill MyConfig and in the Program.cs file just call that method:
app.MapControllers();
app.Run();
CallYourMethodHere(); <-----
another is you can do this:
first create a static class:
public static class MyConfig
{
private static Dictionary<string, string> MyConfigs {set; get;}
private static Dictionary<string, string> GetConfigFromDatabase(bool forceToFill)
{
if(MyConfigs == null || MyConfigs.Any() == false || forceToFill == true)
{
//Fetch Data From Database and Fill MyConfig
}
}
public static string GetConfig(string configName)
{
return GetConfigFromDatabase(false)[configName];
}
}
In solution 2 you have to consider some thread-safe and race condition concepts.
I'm working on .NET Core Web Api application and recently implemented IMemoryCache caching and BackgroundService to refresh the cache every hour. The cache expiration is 2hrs, so it should never go to the db during regular HTTP request. This is my cache class and refresh service:
public class FooCache : IFooCache
{
private readonly IMemoryCache _cache;
private readonly string _key = "Foo";
private readonly int _durationInHours = 2;
private static readonly SemaphoreSlim Semaphore = new SemaphoreSlim(1, 1);
public FooCache(IMemoryCache cache)
{
_cache = cache;
}
public bool TryGetFoo(out List<FooOutput> values)
{
try
{
Semaphore.Wait();
return _cache.TryGetValue(_key, out values);
}
finally
{
Semaphore.Release();
}
}
public void SetFoo(List<FooOutput> values)
{
try
{
Semaphore.Wait();
_cache.Set(_key, values, DateTimeOffset.Now.AddHours(_durationInHours));
}
finally
{
Semaphore.Release();
}
}
}
public class RefreshFooService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly IFooCache _fooCache;
public RefreshFooService(IServiceProvider serviceProvider, IFooCache fooCache)
{
_serviceProvider = serviceProvider;
_fooCache = fooCache;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _serviceProvider.CreateScope())
{
var fooData = scope.ServiceProvider.GetRequiredService<IFooData>();
var foo = await fooData.GetFoo();
_fooCache.SetFoo(foo);
}
await Task.Delay(3600000, stoppingToken); // Refresh every hour
}
}
}
I don't know how much of memory this object should take, but here's what I noticed: Without caching and BackgroundService the app uses ~200MB. With BackgroundService after first refresh, it takes 2.1GB of memory, after second refresh it takes ~3.5GB (sometimes I see 4GB) and it will stay at this level after following refreshes (assuming no API requests are coming).
I understand that for a brief moment the App stores old and new object in memory, right here:
var fooData = scope.ServiceProvider.GetRequiredService<IFooData>();
var foo = await fooData.GetFoo();
_fooCache.SetFoo(foo);
... the new data is already in foo object, but _fooCache still has the old data.
But, shouldn't GC step in and free up the memory of foo object after it's assigned to cache?? Specially after few hours? What am I missing?
I'm developing .NET Core 2.0 Web API and trying to use IDistributedCache to keep some data between different calls.
For this task I created wrapper and registered it as a singleton in Startup.cs file in order to use dependency injection in my controllers.
This is how the wrapper looks (simplified):
public interface ICacheWrapper
{
Task Set<T>(string name, T obj);
Task<T> TryGet<T>(string name);
}
public class CacheWrapper : ICacheWrapper
{
private readonly IDistributedCache _cache;
private readonly TimeSpan _defaultOffset = new TimeSpan(1, 0, 0, 0);
public CacheWrapper(IDistributedCache cache)
{
_cache = cache;
}
public async Task Set<T>(string name, T obj)
{
await DoSet(name, obj);
}
public async Task<T> TryGet<T>(string name)
{
var data = await Get<T>(name);
}
private async Task DoSet<T>(string name, T obj)
{
var binFormatter = new BinaryConverter();
var array = binFormatter.Serialize(obj);
var options = new DistributedCacheEntryOptions { SlidingExpiration = _defaultOffset };
await _cache.SetAsync(name, array, options);
}
private async Task<T> Get<T>(string name)
{
var binFormatter = new BinaryConverter();
var data = await _cache.GetAsync(name);
if (data == null)
{
return default(T);
}
var obj = binFormatter.Deserialize<T>(data);
return obj;
}
}
I also added this line to my Startup.cs file: services.AddDistributedMemoryCache();
The problem is: between each API call IDistributedCache object seems to reset - it does not contain any data. What should I do to keep the cache between calls?
Edit: I can confirm that adding to cache works in scope of one call, after doing SetAsync cache contains one item.
Edit2 This is how I register my wrapper : services.AddSingleton<ICacheWrapper, CacheWrapper>();
I'm working on a project that computes a continuous flow of data.
I've been strugling lately with some memory and networking exceptions to the point where I ask myself if the way i'm getting the data from my database is good.
I am using:
.NET 4.6.1
Akka.NET 1.0.8
RavenDB.Client 3.5.1
Here's an example of how I load data into my actors:
public class MyActor : ReceiveActor
{
public MyActor (ImmutableRegistration registration)
{
Receives();
Self.Tell(new InitDBCache());
}
private void Receives()
{
Receive<InitDBCache>(t =>
{
var builder = new DataBaseCacheBuilder();
builder.BuildFor(registration).ContinueWith(result =>
{
return new DBCacheReceived(result.Result);
},
TaskContinuationOptions.AttachedToParent &
TaskContinuationOptions.ExecuteSynchronously).PipeTo(Self);
});
Receive<DBCacheReceived>(msg =>
{
// Init actor with retrieved data
});
}
private sealed class InitDBCache
{
public InitDBCache() { }
}
private sealed class DBCacheReceived
{
public DBCacheReceived(DataBaseCache cache)
{
this.Cache = cache;
}
public DataBaseCache Cache { get; }
}
}
The DataBaseCacheBuilder goes like this :
public sealed class DataBaseCacheBuilder
{
public DataBaseCacheBuilder()
{
}
public async Task<DataBaseCache> BuildFor(ImmutableRegistration registration)
{
// I have a repository pattern on top of the ravendb client
using (var session = OutsideRefs.DataStore.OpenRavenDbSession())
{
var queryResult1 = await session.repository1.executeQueryAsync(registration.Id);
var queryResult2 = await session.repository2.executeQueryAsync(registration.Id);
return new DataBaseCache(queryResult1, queryResult2);
}
}
}
Concretely, my program throws a fair number of
"System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
Those exceptions are throwed by the ravendb client.
Does anyone see a problem or a correlation with my code and the exception ?
Does using async/await to regroup async calls a bad thing to do even though I'm piping the result ?
How can I use .NET Core's default dependency injection in Hangfire?
I am new to Hangfire and searching for an example which works with ASP.NET Core.
See full example on GitHub https://github.com/gonzigonz/HangfireCore-Example.
Live site at http://hangfirecore.azurewebsites.net/
Make sure you have the Core version of Hangfire:
dotnet add package Hangfire.AspNetCore
Configure your IoC by defining a JobActivator. Below is the config for use with the default asp.net core container service:
public class HangfireActivator : Hangfire.JobActivator
{
private readonly IServiceProvider _serviceProvider;
public HangfireActivator(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public override object ActivateJob(Type type)
{
return _serviceProvider.GetService(type);
}
}
Next register hangfire as a service in the Startup.ConfigureServices method:
services.AddHangfire(opt =>
opt.UseSqlServerStorage("Your Hangfire Connection string"));
Configure hangfire in the Startup.Configure method. In relationship to your question, the key is to configure hangfire to use the new HangfireActivator we just defined above. To do so you will have to provide hangfire with the IServiceProvider and this can be achieved by just adding it to the list of parameters for the Configure method. At runtime, DI will providing this service for you:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IServiceProvider serviceProvider)
{
...
// Configure hangfire to use the new JobActivator we defined.
GlobalConfiguration.Configuration
.UseActivator(new HangfireActivator(serviceProvider));
// The rest of the hangfire config as usual.
app.UseHangfireServer();
app.UseHangfireDashboard();
}
When you enqueue a job, use the registered type which usually is your interface. Don't use a concrete type unless you registered it that way. You must use the type registered with your IoC else Hangfire won't find it.
For Example say you've registered the following services:
services.AddScoped<DbManager>();
services.AddScoped<IMyService, MyService>();
Then you could enqueue DbManager with an instantiated version of the class:
BackgroundJob.Enqueue(() => dbManager.DoSomething());
However you could not do the same with MyService. Enqueuing with an instantiated version would fail because DI would fail as only the interface is registered. In this case you would enqueue like this:
BackgroundJob.Enqueue<IMyService>( ms => ms.DoSomething());
DoritoBandito's answer is incomplete or deprecated.
public class EmailSender {
public EmailSender(IDbContext dbContext, IEmailService emailService)
{
_dbContext = dbContext;
_emailService = emailService;
}
}
Register services:
services.AddTransient<IDbContext, TestDbContext>();
services.AddTransient<IEmailService, EmailService>();
Enqueue:
BackgroundJob.Enqueue<EmailSender>(x => x.Send(13, "Hello!"));
Source:
http://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html
Note: if you want a full sample, see my blog post on this.
All of the answers in this thread are wrong/incomplete/outdated. Here's an example with ASP.NET Core 3.1 and Hangfire.AspnetCore 1.7.
Client:
//...
using Hangfire;
// ...
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddHangfire(config =>
{
// configure hangfire per your requirements
});
}
}
public class SomeController : ControllerBase
{
private readonly IBackgroundJobClient _backgroundJobClient;
public SomeController(IBackgroundJobClient backgroundJobClient)
{
_backgroundJobClient = backgroundJobClient;
}
[HttpPost("some-route")]
public IActionResult Schedule([FromBody] SomeModel model)
{
_backgroundJobClient.Schedule<SomeClass>(s => s.Execute(model));
}
}
Server (same or different application):
{
//...
services.AddScoped<ISomeDependency, SomeDependency>();
services.AddHangfire(hangfireConfiguration =>
{
// configure hangfire with the same backing storage as your client
});
services.AddHangfireServer();
}
public interface ISomeDependency { }
public class SomeDependency : ISomeDependency { }
public class SomeClass
{
private readonly ISomeDependency _someDependency;
public SomeClass(ISomeDependency someDependency)
{
_someDependency = someDependency;
}
// the function scheduled in SomeController
public void Execute(SomeModel someModel)
{
}
}
As far as I am aware, you can use .net cores dependency injection the same as you would for any other service.
You can use a service which contains the jobs to be executed, which can be executed like so
var jobId = BackgroundJob.Enqueue(x => x.SomeTask(passParamIfYouWish));
Here is an example of the Job Service class
public class JobService : IJobService
{
private IClientService _clientService;
private INodeServices _nodeServices;
//Constructor
public JobService(IClientService clientService, INodeServices nodeServices)
{
_clientService = clientService;
_nodeServices = nodeServices;
}
//Some task to execute
public async Task SomeTask(Guid subject)
{
// Do some job here
Client client = _clientService.FindUserBySubject(subject);
}
}
And in your projects Startup.cs you can add a dependency as normal
services.AddTransient< IClientService, ClientService>();
Not sure this answers your question or not
Currently, Hangfire is deeply integrated with Asp.Net Core. Install Hangfire.AspNetCore to set up the dashboard and DI integration automatically. Then, you just need to define your dependencies using ASP.NET core as always.
If you are trying to quickly set up Hangfire with ASP.NET Core (tested in ASP.NET Core 2.2) you can also use Hangfire.MemoryStorage. All the configuration can be performed in Startup.cs:
using Hangfire;
using Hangfire.MemoryStorage;
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(opt => opt.UseMemoryStorage());
JobStorage.Current = new MemoryStorage();
}
protected void StartHangFireJobs(IApplicationBuilder app, IServiceProvider serviceProvider)
{
app.UseHangfireServer();
app.UseHangfireDashboard();
//TODO: move cron expressions to appsettings.json
RecurringJob.AddOrUpdate<SomeJobService>(
x => x.DoWork(),
"* * * * *");
RecurringJob.AddOrUpdate<OtherJobService>(
x => x.DoWork(),
"0 */2 * * *");
}
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
StartHangFireJobs(app, serviceProvider)
}
Of course, everything is store in memory and it is lost once the application pool is recycled, but it is a quick way to see that everything works as expected with minimal configuration.
To switch to SQL Server database persistence, you should install Hangfire.SqlServer package and simply configure it instead of the memory storage:
services.AddHangfire(opt => opt.UseSqlServerStorage(Configuration.GetConnectionString("Default")));
I had to start HangFire in main function. This is how I solved it:
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var serviceScope = host.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
try
{
var liveDataHelper = services.GetRequiredService<ILiveDataHelper>();
var justInitHangfire = services.GetRequiredService<IBackgroundJobClient>();
//This was causing an exception (HangFire is not initialized)
RecurringJob.AddOrUpdate(() => liveDataHelper.RePopulateAllConfigDataAsync(), Cron.Daily());
// Use the context here
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Can't start " + nameof(LiveDataHelper));
}
}
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Actually there is an easy way for dependency injection based job registration.
You just need to use the following code in your Startup:
public class Startup {
public void Configure(IApplicationBuilder app)
{
var factory = app.ApplicationServices
.GetService<IServiceScopeFactory>();
GlobalConfiguration.Configuration.UseActivator(
new Hangfire.AspNetCore.AspNetCoreJobActivator(factory));
}
}
However i personally wanted a job self registration including on demand jobs (recurring jobs which are never executed, except by manual trigger on hangfire dashboard), which was a little more complex then just that. I was (for example) facing issues with the job service activation, which is why i decided to share most of my implementation code.
//I wanted an interface to declare my jobs, including the job Id.
public interface IBackgroundJob {
string Id { get; set; }
void Invoke();
}
//I wanted to retrieve the jobs by id. Heres my extension method for that:
public static IBackgroundJob GetJob(
this IServiceProvider provider,
string jobId) => provider
.GetServices<IBackgroundJob>()
.SingleOrDefault(j => j.Id == jobId);
//Now i needed an invoker for these jobs.
//The invoker is basically an example of a dependency injected hangfire job.
internal class JobInvoker {
public JobInvoker(IServiceScopeFactory factory) {
Factory = factory;
}
public IServiceScopeFactory Factory { get; }
public void Invoke(string jobId)
{
//hangfire jobs should always be executed within their own scope.
//The default AspNetCoreJobActivator should technically already do that.
//Lets just say i have trust issues.
using (var scope = Factory.CreateScope())
{
scope.ServiceProvider
.GetJob(jobId)?
.Invoke();
}
}
//Now i needed to tell hangfire to use these jobs.
//Reminder: The serviceProvider is in IApplicationBuilder.ApplicationServices
public static void RegisterJobs(IServiceProvider serviceProvider) {
var factory = serviceProvider.GetService();
GlobalConfiguration.Configuration.UseActivator(new Hangfire.AspNetCore.AspNetCoreJobActivator(factory));
var manager = serviceProvider.GetService<IRecurringJobManager>();
var config = serviceProvider.GetService<IConfiguration>();
var jobs = serviceProvider.GetServices<IBackgroundJob>();
foreach (var job in jobs) {
var jobConfig = config.GetJobConfig(job.Id);
var schedule = jobConfig?.Schedule; //this is a cron expression
if (String.IsNullOrWhiteSpace(schedule))
schedule = Cron.Never(); //this is an on demand job only!
manager.AddOrUpdate(
recurringJobId: job.Id,
job: GetJob(job.Id),
cronExpression: schedule);
}
//and last but not least...
//My Method for creating the hangfire job with injected job id
private static Job GetJob(string jobId)
{
var type = typeof(JobInvoker);
var method = type.GetMethod("Invoke");
return new Job(
type: type,
method: method,
args: jobId);
}
Using the above code i was able to create hangfire job services with full dependency injection support. Hope it helps someone.
Use the below code for Hangfire configuration
using eForms.Core;
using Hangfire;
using Hangfire.SqlServer;
using System;
using System.ComponentModel;
using System.Web.Hosting;
namespace eForms.AdminPanel.Jobs
{
public class JobManager : IJobManager, IRegisteredObject
{
public static readonly JobManager Instance = new JobManager();
//private static readonly TimeSpan ZeroTimespan = new TimeSpan(0, 0, 10);
private static readonly object _lockObject = new Object();
private bool _started;
private BackgroundJobServer _backgroundJobServer;
private JobManager()
{
}
public int Schedule(JobInfo whatToDo)
{
int result = 0;
if (!whatToDo.IsRecurring)
{
if (whatToDo.Delay == TimeSpan.Zero)
int.TryParse(BackgroundJob.Enqueue(() => Run(whatToDo.JobId, whatToDo.JobType.AssemblyQualifiedName)), out result);
else
int.TryParse(BackgroundJob.Schedule(() => Run(whatToDo.JobId, whatToDo.JobType.AssemblyQualifiedName), whatToDo.Delay), out result);
}
else
{
RecurringJob.AddOrUpdate(whatToDo.JobType.Name, () => RunRecurring(whatToDo.JobType.AssemblyQualifiedName), Cron.MinuteInterval(whatToDo.Delay.TotalMinutes.AsInt()));
}
return result;
}
[DisplayName("Id: {0}, Type: {1}")]
[HangFireYearlyExpirationTime]
public static void Run(int jobId, string jobType)
{
try
{
Type runnerType;
if (!jobType.ToType(out runnerType)) throw new Exception("Provided job has undefined type");
var runner = runnerType.CreateInstance<JobRunner>();
runner.Run(jobId);
}
catch (Exception ex)
{
throw new JobException($"Error while executing Job Id: {jobId}, Type: {jobType}", ex);
}
}
[DisplayName("{0}")]
[HangFireMinutelyExpirationTime]
public static void RunRecurring(string jobType)
{
try
{
Type runnerType;
if (!jobType.ToType(out runnerType)) throw new Exception("Provided job has undefined type");
var runner = runnerType.CreateInstance<JobRunner>();
runner.Run(0);
}
catch (Exception ex)
{
throw new JobException($"Error while executing Recurring Type: {jobType}", ex);
}
}
public void Start()
{
lock (_lockObject)
{
if (_started) return;
if (!AppConfigSettings.EnableHangFire) return;
_started = true;
HostingEnvironment.RegisterObject(this);
GlobalConfiguration.Configuration
.UseSqlServerStorage("SqlDbConnection", new SqlServerStorageOptions { PrepareSchemaIfNecessary = false })
//.UseFilter(new HangFireLogFailureAttribute())
.UseLog4NetLogProvider();
//Add infinity Expiration job filter
//GlobalJobFilters.Filters.Add(new HangFireProlongExpirationTimeAttribute());
//Hangfire comes with a retry policy that is automatically set to 10 retry and backs off over several mins
//We in the following remove this attribute and add our own custom one which adds significant backoff time
//custom logic to determine how much to back off and what to to in the case of fails
// The trick here is we can't just remove the filter as you'd expect using remove
// we first have to find it then save the Instance then remove it
try
{
object automaticRetryAttribute = null;
//Search hangfire automatic retry
foreach (var filter in GlobalJobFilters.Filters)
{
if (filter.Instance is Hangfire.AutomaticRetryAttribute)
{
// found it
automaticRetryAttribute = filter.Instance;
System.Diagnostics.Trace.TraceError("Found hangfire automatic retry");
}
}
//Remove default hangefire automaticRetryAttribute
if (automaticRetryAttribute != null)
GlobalJobFilters.Filters.Remove(automaticRetryAttribute);
//Add custom retry job filter
GlobalJobFilters.Filters.Add(new HangFireCustomAutoRetryJobFilterAttribute());
}
catch (Exception) { }
_backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions
{
HeartbeatInterval = new System.TimeSpan(0, 1, 0),
ServerCheckInterval = new System.TimeSpan(0, 1, 0),
SchedulePollingInterval = new System.TimeSpan(0, 1, 0)
});
}
}
public void Stop()
{
lock (_lockObject)
{
if (_backgroundJobServer != null)
{
_backgroundJobServer.Dispose();
}
HostingEnvironment.UnregisterObject(this);
}
}
void IRegisteredObject.Stop(bool immediate)
{
Stop();
}
}
}
Admin Job Manager
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
if (Core.AppConfigSettings.EnableHangFire)
{
JobManager.Instance.Start();
new SchedulePendingSmsNotifications().Schedule(new Core.JobInfo() { JobId = 0, JobType = typeof(SchedulePendingSmsNotifications), Delay = TimeSpan.FromMinutes(1), IsRecurring = true });
}
}
protected void Application_End(object sender, EventArgs e)
{
if (Core.AppConfigSettings.EnableHangFire)
{
JobManager.Instance.Stop();
}
}
}