2

我在将当前登录用户注入我的服务层时遇到问题,我正在尝试类似于代码营服务器的东西,但很难弄清楚为什么我的代码不起作用......

我的应用程序:UI 层 -> 连接到域服务 -> 连接到 Repo 层...

Repo 未连接到 UI,所有内容都经过检查验证并从 DomainService 层传回......

我的代码:

//这是在我的域服务中声明的

public interface IUserSession
{
    UserDTO GetCurrentUser();
}

在我的 Web 应用程序中,我想实现这个服务,然后将它注入到我的服务层中(这就是我卡住的地方):

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);
    }


}

我想做的是:从身份验证服务中获取登录用户,但是这不起作用,所以我删除了代码......

我绑定 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 的服务时遇到异常,它说请为控制器 x 提供默认的无参数构造函数,但是如果我从域服务中删除引用,一切正常......

服务总监:

 private IReadOnlyRepository _repo;
    private IUserSession _session;
    public ActivityService(IReadOnlyRepository repo, IUserSession _session)
    {
      this._repo = repo;
      this._session = _session;
     }

有没有更好的方法/更简单的方法来实现这个?

在下面回复的帮助下更新我设法完成了这项工作,如果有人想知道我是如何做到的,我已经上传到 github...

https://gist.github.com/1042173

4

1 回答 1

0

我假设您正在使用 NinjectHttpApplication,因为您已经覆盖了 OnApplicationStarted?如果没有,你应该是,因为它会为你注册控制器到 Ninject。如果这没有发生,那么您可能会看到您看到的错误。

以下是我在我的应用程序中如何做到这一点:

控制器基础:

    [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;
        }
    }

让我知道这是否没有意义。

于 2011-06-16T13:42:24.190 回答