You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
3.0 KiB
83 lines
3.0 KiB
using Infrastructure.Application.Entites.Settings;
|
|
using Infrastructure.Data;
|
|
using Infrastructure.Extensions;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using System;
|
|
using System.Globalization;
|
|
using System.Linq;
|
|
|
|
namespace Infrastructure.Application.Services.Settings
|
|
{
|
|
public class CachedSettingService : ISettingService
|
|
{
|
|
private readonly IServiceProvider _sp;
|
|
private readonly string _keyTemplate = "iot-setting-{0}";
|
|
|
|
public CachedSettingService(IServiceProvider sp)
|
|
{
|
|
this._sp = sp;
|
|
}
|
|
|
|
public Setting GetSetting(string name)
|
|
{
|
|
var key = string.Format(CultureInfo.InvariantCulture, _keyTemplate, name);
|
|
using var scope = this._sp.CreateScope();
|
|
var cache = scope.ServiceProvider.GetRequiredService<IDistributedCache>();
|
|
var setting = cache.Get<Setting>(key);
|
|
if (setting == null)
|
|
{
|
|
var repo = scope.ServiceProvider.GetRequiredService<IRepository<Setting>>();
|
|
setting = repo.ReadOnlyTable().FirstOrDefault(o => o.Name == name);
|
|
cache.Set(key, setting);
|
|
}
|
|
return setting;
|
|
}
|
|
|
|
public void AddSetting(Setting setting)
|
|
{
|
|
using var scope = this._sp.CreateScope();
|
|
var repo = scope.ServiceProvider.GetRequiredService<IRepository<Setting>>();
|
|
repo.Add(setting);
|
|
repo.SaveChanges();
|
|
}
|
|
|
|
public void DeleteSetting(Setting setting)
|
|
{
|
|
if (setting is null)
|
|
{
|
|
throw new ArgumentNullException(nameof(setting));
|
|
}
|
|
var key = string.Format(CultureInfo.InvariantCulture, _keyTemplate, setting.Name);
|
|
using var scope = this._sp.CreateScope();
|
|
var repo = scope.ServiceProvider.GetRequiredService<IRepository<Setting>>();
|
|
var entity = repo.Table().FirstOrDefault(o => o.Id == setting.Id);
|
|
repo.Delete(entity);
|
|
repo.SaveChanges();
|
|
var cache = scope.ServiceProvider.GetRequiredService<IDistributedCache>();
|
|
cache.Remove(key);
|
|
}
|
|
|
|
public void UpdateSetting(Setting setting)
|
|
{
|
|
if (setting is null)
|
|
{
|
|
throw new ArgumentNullException(nameof(setting));
|
|
}
|
|
var key = string.Format(CultureInfo.InvariantCulture, _keyTemplate, setting.Name);
|
|
using var scope = this._sp.CreateScope();
|
|
var repo = scope.ServiceProvider.GetRequiredService<IRepository<Setting>>();
|
|
var entity = repo.Table().FirstOrDefault(o => o.Id == setting.Id);
|
|
entity.From(setting);
|
|
repo.SaveChanges();
|
|
var cache = scope.ServiceProvider.GetRequiredService<IDistributedCache>();
|
|
cache.Remove(key);
|
|
}
|
|
|
|
public string GetValue(string name)
|
|
{
|
|
return this.GetSetting(name)?.Value;
|
|
}
|
|
}
|
|
}
|