Reputation: 655
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!
Upvotes: 0
Views: 149
Reputation:
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)
Upvotes: 1
Reputation: 119
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 )
Upvotes: 1