Everywhere in my application i often have to grab the same information (current logged in user) and declare the same services (authorization, settings etc). So far i have combated this problem by doing the following in my Global.asax file:
public class App : HttpApplication {
private static IMembershipService _membershipService;
public static IAuthorizationService Authorization;
public static ISettingsService Settings;
public static User CurrentUser {
get { return HttpContext.Current.User.Identity.IsAuthenticated ? _membershipService.GetUser(((UserIdentity)HttpContext.Current.User.Identity).Id) : null; }
}
protected void Application_Start() {
// Create the ioc container
var container = new UnityContainer();
... Register Types Here
_membershipService = container.Resolve<IMembershipService>();
Authorization = container.Resolve<IAuthorizationService>();
Settings = container.Resolve<ISettingsService>();
}
}
Now to access the current logged in user i simply have to say App.CurrentUser. Note although it is declared static the get is not cached into a static variable and therefore it is different for each request.
I was just wondering if this is a good solution. There’s something i don’t like about it but i’d appreciate the opinions of some ASP.NET experts.
Thanks
this is an abuse of the static keyword, especially since you are using an IoC container.
assuming this is an MVC app you should only need a very limited number of calls to the container. The primary call would be the controller factory that would resolve the controller from the container. there may be a few other places to call the continer, but ideally only one.
if this is webforms you could setup a base class with protected read-only properties to resolve components in the ctor or page_init event. not ideal, but a step in the right direction.
the other thing to consider is that static classes imply singletons. in which case the components cannot have state. otherwise you get into all kinds of bugs with shared state and race conditions.
I find it’s best to using transient objects as much as possible, and only keep them around for a short time. lower memory consumption and the object can be tailored to the context in which it’s used.