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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With