Unity MVC注入当前用户
问题描述:
我正在使用基本的Unity MVC Nuget Bootstrapper。 我想在注入当前登录的用户进入服务我定义Unity MVC注入当前用户
_container.RegisterType<IDoSomethingService, DoSomethingService>();
这样DoSomethingService得到一个ICurrentUser物体或某种形式的解析器。
我试图避免拨打电话一样
DoSomethingService.DoSomething(currentUserUsingService,...);
或者在所有的MVC控制器的构造还避免设置:
DoSomethingService.CurrentUSer = User.Identity.Name;
答
在我的项目中我用下一个:
public interface ICurrentUserService
{
int? GetId();
}
我注册下一个执行:
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>();
并使我的服务取决于ICurrentUserService(通过使用ctor参数)或将userId传递到我在控制器中的服务的方法。