我在将当前登录用户注入(inject)我的服务层时遇到问题,我正在尝试类似于代码训练营服务器的方法,但努力弄清楚为什么我的代码不起作用...
我的应用程序:UI 层 -> 连接到域服务 -> 连接到 Repo 层...
Repo 未连接到 UI,所有内容都经过检查验证并从 DomainService 层传回...
我的代码:
//这是在我的域服务中声明的
public interface IUserSession
{
UserDTO GetCurrentUser();
}
在我的 Web 应用程序中,我想实现此服务,然后将其注入(inject)我的服务层(这就是我卡住的地方):
public class UserSession : IUserSession
{
//private IAuthorizationService _auth;
public UserSession()//IAuthorizationService _auth)
{
//this._auth = _auth;
}
public UserDTO GetCurrentUser()
{
var identity = HttpContext.Current.User.Identity;
if (!identity.IsAuthenticated)
{
return null;
}
return null;
//return _auth.GetLoggedOnUser(identity.Name);
}
}
我想做的是:从身份验证服务获取登录用户,但是这不起作用,所以我删除了代码...
我将所有内容绑定(bind)到 global.asax 中,如下所示:
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
// hand over control to NInject to register all controllers
RegisterRoutes(RouteTable.Routes);
Container.Get<ILoggingService>().Info("Application started");
//here is the binding...
Container.Bind<IUserSession>().To<UserSession>();
}
首先:当我尝试使用使用 IUserSession 的服务时出现异常,它说请为 Controller x 提供默认的无参数构造函数,但是如果我从域服务中删除引用,一切正常...
服务人员:
private IReadOnlyRepository _repo;
private IUserSession _session;
public ActivityService(IReadOnlyRepository repo, IUserSession _session)
{
this._repo = repo;
this._session = _session;
}
有没有更好/更简单的方法来实现这个?
UPATE 在下面回复的帮助下,我设法完成了这项工作,如果有人想知道我是怎么做到的,我已经上传到 gituhub 上...
最佳答案
我假设您正在使用 NinjectHttpApplication,因为您已经覆盖了 OnApplicationStarted?如果没有,你应该是,因为它会用 Ninject 为你注册 Controller 。如果这没有发生,那么您会得到您所看到的错误。
以下是我在我的应用程序中的做法:
Controller 库:
[Inject]
public IMembershipProvider Membership { get; set; }
public Member CurrentMember
{
get { return Membership.GetCurrentUser() as Member; }
}
IMembershipProvider:
public Member GetCurrentUser()
{
if ( string.IsNullOrEmpty( authentication.CurrentUserName ) )
return null;
if ( _currentUser == null )
{
_currentUser = repository.GetByName( authentication.CurrentUserName );
}
return _currentUser;
}
private Member _currentUser;
IAuthenticationProvider:
public string CurrentUserName
{
get
{
var context = HttpContext.Current;
if ( context != null && context.User != null && context.User.Identity != null )
return HttpContext.Current.User.Identity.Name;
else
return null;
}
}
如果这没有意义,请告诉我。
关于c# - 使用 Ninject 将当前用户注入(inject)我的域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6369928/