lundi 5 janvier 2015

Getting Current User Without Global Reference

I have a service call DataManager that needs a reference to the current IPrincipal user. However, I don't want to use a global reference like System.Threading.Thread.CurrentPrincipal or HttpContext.Current.User because I want to be able to unit test it and specify any user for any given test. But I also don't want to construct a new DataManager for each thread in a multi-threaded environment (like WebApi or Web Services).


Is it bad practice or will it break anything if I inject (via constructor) an IPrincipal implementation that internally uses HttpContext.Current.User or HttpContext.Current.User? Otherwise how should I handle this?


The solution I am thinking of looks like this:



public class DataManager {
public DataManager(IPrincipal currentUser){
this.currentUser = currentUser;
}
private IPrincipal currentUser;
...
public void DoWork(){
var currentUserName = currentUser.Identity.Name;
// Do work here
}
}


And then, when using this in ASP.NET, pass in an IPrincipal implementation that references the HTTP context's current user:



public class CurrentUser : IPrincipal {
public IIdentity Identity {
get {
return HttpContext.Current.User.Identity;
}
}
public bool IsInRole(string role) {
return HttpContext.Current.User.IsInRole(role);
}
}

Aucun commentaire:

Enregistrer un commentaire