2
votes

Using Unity in an ASP.Net MVC 2 app I have various dependencies on Controllers instantiated correctly. However, I want to ensure that the current IPrincipal for the user is going to be passed via injection to lower level Services, Repository etc.

Therefore in a lower level service I have something like:

[Dependency] IPrincipal CurrentUser {get; set;}

If I use Property Dependency Injection I do not get what I want because the Controller is instantiated BEFORE a User principal is available and in any case Unity does not know to get the current user credentials.

So what I want is to be able to inject the current user's IPrincipal (or probably RolePrincipal) into one of the dependencies for the Controller.

How can I do this?

3
Thanks for the answers mrjoltcola and mnemosyn. I agree with the comments about dependency injection. The idea I am working on is to have this automatically be present in the service and repository so as not to have extra code in the Controller class every time the developer is going off to update the database. As this is related to Audit I want to ensure the run-time user is always available and that the developer doesn't have to remember to pass it through.Redeemed1

3 Answers

7
votes

Why not take the direct route, and just assign it.

Thread.CurrentPrincipal = user;

Dependency injection is good, but don't let it get in the way of the best dependency injector, the programmer.

2
votes

While this thread is old, it looks like Jon Kruger has an answer that seems to directly answer the original question: http://jonkruger.com/blog/2009/04/13/hiding-threadcurrentprincipal-from-your-code/

0
votes

Why inject it? The current principal is already present as User. That is what we use, and it works fine so far. The user shouldn't change within a single request, should it?

protected void Application_AuthenticateRequest()
{
    var ticket = GetAuthenticationTicket();
    // Perform actual authentication, etc.
    MyUser user = BigAuthStuff();
    Context.User = user;
    Thread.CurrentPrincipal = user;
}

public class MyBaseController : Controller
{
    protected MyUser AuthenticatedUser
    {
        get { return User as MyUser; }
    }
}