Search code examples
c#nancy

How to keep member variables or properties on nancy module's side?


I would like to know if it's possible to keep member variables or public properties under a NancyModule.

Here's a simple example of what I think should work but doesn't.

public class MyModule : NancyModule
{
    public List<string> MyList { get; set; } = new List<string>();//Problem

    public MyModule()
    {
        #region Get
        Get("/index", args => GetIndex("user"));
        #endregion

        #region Post
        Post("/postUser", args => PostUser("user"));
        #endregion
    }

    private int GetIndex(string user)
    {
        return MyList.IndexOf(user);//Problem
    }

    private int PostUser(string user)
    {
        MyList.Add(user);//Problem

        return MyList.IndexOf(user);//Problem
    }
}

Through debugging, I saw that every time I send a POST or a GET to my running NancyHost, the whole NancyModule is parsed or recalled... So I think my list is reset to a new list of strings every time.

I'm kinda new to nancy and I'm definitely doing something wrong. Is it even possible keep such a variable within this module?


Solution

  • You could make MyList static.

    public static List<string> MyList { get; set; } = new List<string>();

    An instance of each NancyModule is created at startup and then as HTTP requests come in an instance of the NancyModule that should handle the request is created. So yes, a new instance of your module is created per request. That means that sharing state between requests must be done by other means that instance variable/properties - could be a database, could be static variables.