How to preserve the value of a variable between Rest requests RRS feed

  • Question

  • For each HandleEvent the _newProduct would be set to true, but while I get HandleAnotherEvent the value of this _newProduct is becoming false. How to preserve this? I dont want to use static variable? Is there any other way?

    public sealed class ProductNotificationHandler : INotificationHandler<HandleEvent>, INotificationHandler<HandleAnotherEvent>


    private bool _newProduct = false;

    public async Task Handle(HandleEvent eventNotification, CancellationToken cancellationToken)

               _newProduct = eventNotification.NewProduct


    public async Task Handle(HandleAnotherEvent eventNotification, CancellationToken cancellationToken)

               if(_newProduct)} //do logic



    public class PublishNotification() : IPublishNotification


    _mediator.Publish(new HandleEvent{ NewProduct= true;}, CancellationToken.None);







    Friday, August 28, 2020 12:13 PM

All replies

  • Hi KGKrishna,
    The Visual C# forum discusses and asks questions about the C# programming language, IDE, libraries, samples, and tools.
    Based on your description, I suggest you go to ASP.NET forum for more professional answer.
    Thank you for your understanding.
    Best Regards,
    Daniel Zhang

    "Windows Forms General" forum will be migrating to a new home on Microsoft Q&A (Preview)!
    We invite you to post new questions in the "Windows Forms General" forum’s new home on Microsoft Q&A (Preview)!
    For more information, please refer to the sticky post.

    Monday, August 31, 2020 7:32 AM
  • Hi,

    since you are relying meditor pattern, I think that using a cache dictionary exposed as a singleton should be a good way to store last state:

    public class StateHandler{ private StateHandler(){ LastState = new Dictionary<string, object>(); } private StateHandler _instance; public static StateHandler DefaultStateHandler { get {

    // you can use lock block:

    // lock(new objecy()){ ... > _instance = _instance ?? new StateHandler(); return _instance;

    // ... > } } } public Dictionary<string, object> LastState { get; private set; } public void SetValue(string key, object value) { LastState.Add(key, value); } }

    and then register it as singleton and use it to store/get last state.

    here is an article about sharing context by M. Jimmy Bogard: https://jimmybogard.com/sharing-context-in-mediatr-pipelines/

    best regards.

    Monday, August 31, 2020 11:55 AM