using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Volo.Abp;
using Volo.Abp.DependencyInjection;
namespace Sanhe.Abp.Notifications;
///
/// 通知定义管理者接口
///
public class NotificationDefinitionManager : INotificationDefinitionManager, ISingletonDependency
{
protected AbpNotificationsOptions Options { get; }
protected IDictionary NotificationGroupDefinitions => _lazyNotificationGroupDefinitions.Value;
private readonly Lazy> _lazyNotificationGroupDefinitions;
protected IDictionary NotificationDefinitions => _lazyNotificationDefinitions.Value;
private readonly Lazy> _lazyNotificationDefinitions;
private readonly IServiceScopeFactory _serviceScopeFactory;
public NotificationDefinitionManager(
IOptions optionsAccessor,
IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
Options = optionsAccessor.Value;
_lazyNotificationDefinitions = new Lazy>(
CreateNotificationDefinitions,
isThreadSafe: true
);
_lazyNotificationGroupDefinitions = new Lazy>(
CreateNotificationGroupDefinitions,
isThreadSafe: true
);
}
public virtual NotificationDefinition Get(string name)
{
Check.NotNull(name, nameof(name));
var feature = GetOrNull(name);
if (feature == null)
{
throw new AbpException("Undefined notification: " + name);
}
return feature;
}
public virtual IReadOnlyList GetAll()
{
return NotificationDefinitions.Values.ToImmutableList();
}
public virtual NotificationDefinition GetOrNull(string name)
{
return NotificationDefinitions.GetOrDefault(name);
}
public IReadOnlyList GetGroups()
{
return NotificationGroupDefinitions.Values.ToImmutableList();
}
protected virtual Dictionary CreateNotificationDefinitions()
{
var notifications = new Dictionary();
foreach (var groupDefinition in NotificationGroupDefinitions.Values)
{
foreach (var notification in groupDefinition.Notifications)
{
if (notifications.ContainsKey(notification.Name))
{
throw new AbpException("Duplicate notification name: " + notification.Name);
}
notifications[notification.Name] = notification;
}
}
return notifications;
}
protected virtual Dictionary CreateNotificationGroupDefinitions()
{
var context = new NotificationDefinitionContext();
using (var scope = _serviceScopeFactory.CreateScope())
{
var providers = Options
.DefinitionProviders
.Select(p => scope.ServiceProvider.GetRequiredService(p) as INotificationDefinitionProvider)
.ToList();
foreach (var provider in providers)
{
provider.Define(context);
}
}
return context.Groups;
}
}