0

I have a user model for a C# web app that I populate in a controller with various properties like username etc.

I'd just like to know if there is a place where I can instantiate this class once and then reuse it in multiple controllers as currently I have it setup so that every single controller creates a new instance of User adds the relevant data to it and passes it to it's view but this doesn't seem efficient!

6
  • Create a BaseController and put you common stuff in its constructor and have all you controllers inherit from BaseController Commented Oct 9, 2015 at 10:24
  • I do like this idea too but perhaps for more area specific things and not across the whole app itself so thanks! Commented Oct 9, 2015 at 10:38
  • 1
    You have accepted an answer for using MemoryCache which is fine for certain global data that wont ever change but its not suitable for storing user data - for that you need session Commented Oct 9, 2015 at 10:41
  • You are correct I do indeed! Commented Oct 9, 2015 at 10:43
  • Suggest you add it to Session in the login method. And in a BaseController you could have a (say) UserData property which gets the object from Session (or if it does not exist, gets it from the database) Commented Oct 9, 2015 at 10:56

2 Answers 2

1

If its a small amount of data consider using a custom IPrincipal (or Claims if your using Identity) so its avaliable in the FormsAuthenticationTicket. Otherwise you can store the data in Session to avoid repeated database calls.

In addition, consider a BaseController class (from which all your controllers inherit) which contains a property or method to read the object from Session (and gets the object from the database in case Session has expired or has been recycled)

Sign up to request clarification or add additional context in comments.

Comments

1

you can cache your data using MemoryCache :

public class InMemoryCache: ICacheService
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}

Usage: var user=cacheService.GetOrSet("User", ()=>Repository.GetUser())

Or implement CacheRepository pattern ( CacheRepo pattern description )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.