Создается два экземпляра NotificationListenerService. Как их можно использовать в DependencyInjection?

Есть приложение со встроенным сервисом прослушки уведомлений. Т.к я использую prism, мне необходимо регистрировать этот сервис, который наследуется от моего интерфейса INotificationListenerService. При регистрации я обращаюсь к свойству Current, (т.к. сервис работает даже после закрытия приложения). Если экземпляр отсутствует, возвращается новый. Но после регистрации самостоятельно создается другой экземпляр сервиса, который уже никак не регистрируется в контейнере. И этот второй экземпляр реагирует на появление уведомлений, но на его события уже никак нельзя подписаться.

Вопрос: каким образом можно сделать так, чтобы в контейнер попадал именно второй экземпляр, они каким-либо образом объединялись ил подменяли друг-друга?

Регистрация:

containerRegistry.RegisterInstance<INotificationListenerService>(NotificationListenerService.Current);

Интерфейс:

public interface INotificationListenerService
{
    bool IsListenerConnected { get; }

    public event EventHandler<bool> ConnectionStateChanged;

    public event EventHandler<NotificationEventArgs> NotificationPosted;
}

Класс:

[Service(Label = "Ardulens Notification listener service", Permission = "android.permission.BIND_NOTIFICATION_LISTENER_SERVICE", Exported =true)]
[IntentFilter(new[] { "android.service.notification.NotificationListenerService" })]
public class NotificationListenerService : Android.Service.Notification.NotificationListenerService, INotificationListenerService
{
    public event EventHandler<NotificationEventArgs> NotificationPosted;
    public event EventHandler<bool> ConnectionStateChanged;

    private static NotificationListenerService current;
    public static NotificationListenerService Current
    {
        get
        {
            if (current == null)
            {
                current = new NotificationListenerService();
            }
            return current;
        }
        private set => current = value;
    }

    public bool IsListenerConnected { get; private set; }
    public override void OnListenerConnected()
    {
        base.OnListenerConnected();
        IsListenerConnected = true;
        ConnectionStateChanged?.Invoke(this, IsListenerConnected);
    }

    public override void OnListenerDisconnected()
    {
        base.OnListenerDisconnected();
        IsListenerConnected = false;
        ConnectionStateChanged?.Invoke(this, IsListenerConnected);
    }

    public NotificationListenerService()
    {
        if(current == null)
            Current = this;
    }

    public override void OnCreate()
    {
        base.OnCreate();
    }

    public override void OnNotificationPosted(StatusBarNotification sbn)
    {
         NotificationPosted?.Invoke(this, new NotificationEventArgs(sbn));
         var text = sbn.Notification.Extras.GetCharSequence(Notification.ExtraText);
         var title = sbn.Notification.Extras.GetCharSequence(Notification.ExtraTitle);
         //Log.Debug(TAG, "ID :" + sbn.Id + "t" + sbn.Notification.TickerText + "t" + sbn.PackageName);
         Debug.WriteLine("\ntext: " + text + " title: " + title + "\n");
        
    }
}

Ответы (1 шт):

Автор решения: Andrew Pstvt

Нашел решение: создал дополнительный класс NLService, который наследуется от этого интерфейса и содержит в себе объект NotificationListenerService. В сам NotificationListenerService добавил событие, возникающее при создании класса. В NLService подписался на это событие сохранил новый объект.

Вот, что получилось:

public class NLService : INotificationListenerService
{
    private NotificationListenerService _nlistener; //объект слушателя

    public event EventHandler<bool> ConnectionStateChanged;
    public event EventHandler<NotificationEventArgs> NotificationPosted;

    private static NLService _current;
    public static NLService Current
    {
        get
        {
            if (_current == null)
                _current = new();
            return _current;
        }
        private set => _current = value;
    }

    public bool IsListenerConnected
    {
        get
        {
            if (_nlistener != null)
                return _nlistener.IsListenerConnected;
            return false;
        }
    }

    public NLService()
    {
        NotificationListenerService.NewInstanceCreated += OnNewInstanceCreated;
    }

    private void OnNewInstanceCreated(object sender, NotificationListenerService e)
    {
        _nlistener = e;
        _nlistener.ConnectionStateChanged += (o, e) => ConnectionStateChanged?.Invoke(this, e);
        _nlistener.NotificationPosted += (o, e) => NotificationPosted?.Invoke(this, e);
    }
}


[Service(Label = "Ardulens Notification listener service", Permission = "android.permission.BIND_NOTIFICATION_LISTENER_SERVICE", Exported =true)]
[IntentFilter(new[] { "android.service.notification.NotificationListenerService" })]
class NotificationListenerService : Android.Service.Notification.NotificationListenerService
{
    public event EventHandler<NotificationEventArgs> NotificationPosted;
    public event EventHandler<bool> ConnectionStateChanged;

    public static event EventHandler<NotificationListenerService> NewInstanceCreated;

    public bool IsListenerConnected { get; private set; }
    public override void OnListenerConnected()
    {
        base.OnListenerConnected();
        IsListenerConnected = true;
        ConnectionStateChanged?.Invoke(this, IsListenerConnected);
    }

    public override void OnListenerDisconnected()
    {
        base.OnListenerDisconnected();
        IsListenerConnected = false;
        ConnectionStateChanged?.Invoke(this, IsListenerConnected);
    }

    public NotificationListenerService()
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();
        NewInstanceCreated?.Invoke(this, this);
    }

    public override void OnNotificationPosted(StatusBarNotification sbn)
    {
            NotificationPosted?.Invoke(this, new NotificationEventArgs(sbn));
            var text = sbn.Notification.Extras.GetCharSequence(Notification.ExtraText);
            var title = sbn.Notification.Extras.GetCharSequence(Notification.ExtraTitle);
            //Log.Debug(TAG, "ID :" + sbn.Id + "t" + sbn.Notification.TickerText + "t" + sbn.PackageName);
            Debug.WriteLine("\ntext: " + text + " title: " + title + "\n");
       
    }
}

И при регистрации передаю экземпляр NLService:

containerRegistry.RegisterInstance<INotificationListenerService>(NLService.Current);
→ Ссылка