Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity MVC injecting current user

I am using the basic Unity MVC Nuget Bootstrapper. I would like to Inject the currently logged in user into the services I am defining

_container.RegisterType<IDoSomethingService, DoSomethingService>();

such that DoSomethingService gets an ICurrentUser object or some form of resolver.

I am trying to avoid having to make calls like

DoSomethingService.DoSomething(currentUserUsingService,...);

Or in the constructor of all the MVC Controllers also avoiding setting:

DoSomethingService.CurrentUSer = User.Identity.Name;
like image 656
maxfridbe Avatar asked Jan 20 '26 13:01

maxfridbe


1 Answers

In my projects I use next:

public interface ICurrentUserService
{
    int? GetId();
}

I register next implementation:

public class CurrentUserService: ICurrentUserService
{
    public int? GetId()
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
            return null;
        return int.Parse(HttpContext.Current.User.Identity.Name);//When auth - id stored in cookie
    }
}

_container.RegisterType<ICurrentUserService, CurrentUserService>();

And make my services depends on ICurrentUserService (by using ctor parameter) or pass userId into methods of my services in controllers.