Eliminating static properties - What patterns do I have at my disposal?

I currently have a type that I inject into my controllers that's used for getting and setting session data.

I use this so that I can obtain relevant session information as _sessionData.Username rather than using Session["username"].

I'd like to use this session information across all of my views and would previously have done this by making the SessionData members static instead of injecting the SessionData class into my controller.

I want to avoid using static members as well as having to pass the object to the view in each controller.

What patterns best suit this type of scenario? What do you do to solve this same problem?


Why not just use Session["username"]? You can wrap the static call in an instance like this:

public class MySessionClass
    public string GetSessionValue(String value)
        return Session[value];

You gain the maintenance and flexibility of an instance that can then be mocked in a test without having to rewrite the Session class over again


As far as using your instance in your view, what is stopping you from writing a code-block and newing it up and using it? You should be able to write code against it like any other code nuggets in MVC. However, I would suggest against doing this as it defeats the purpose of tiering your architecture. You can either access the session directly, like you would with any HTML page, or you can pass it through as an object from your controller.

Dependency injection would help you here. Take any dependency injection framework and integrate it with you MVC application. For example to integrate Ninject into you MVC application see this blog post.

Once you integrate a DI framework with you application. Register the SessionData class with the DI framework. Choose a valid lifetime for the SessionData class based on your scenario. If you look at these DI frameworks they provide multiple lifetime configurations such as instance per call, per session, singleton.

Now inject SessionData dependency where ever you want. For controller you can create a BaseController containing this dependency as a public property such as

public SessionData SessionContext {get;set;}

For View part you need to look at passing strongly typed model. The process would be similar here. Create a BaseModel, keep a SessionData property here and DI framework should do the rest. The last step here would be to pass this model to each view rendered.

Need Your Help

How to ignore "Enter username for Private Proxy Access" prompt?

python proxy urllib

I'm using urllib.urlopen with some http proxies and sometimes (probably when they require authorization) I get the following prompt printed into the console:

Querying DBpedia with SPARQL and Jena

sparql semantic-web jena dbpedia

I cannot understand how can I query DBpedia using Jena. In the tutorials like here(Listing 4) model is initialized as follows: