0

我正在开发一个MVC 5 application用于Ninject处理依赖注入的。该应用程序定义了一个SecurityService提供有关当前登录用户的各种信息。我正在使用 Windows 身份验证。

好的,让我们深入研究代码。

NinjectWebCommon.cs

    private static readonly Bootstrapper bootstrapper = new Bootstrapper();
    private static KernelBase kernel;

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start() 
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        kernel = new StandardKernel();
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            RegisterServices(kernel);
            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<ISecurityService>().To<SecurityService>().InRequestScope();

        // custom bindings are defined here
    }

    public static void PerformInjectionOn(object instance)
    {
        kernel.Inject(instance);
    }

请注意kernel.Bind<ISecurityService>().To<SecurityService>().InRequestScope();安全绑定定义。

安全服务.cs

    private AppUser _CurrentUser = null;

    /// <summary>
    /// gets logged user data, based on current identity username (Sam account name)
    /// </summary>
    /// <returns>AppUser object if windows identity maps to an existing active user. Otherwise null</returns>
    public AppUser GetLoggedUserData()
    {
        lock(lockObj)
        {
            String currUsername = WindowsIdentity.GetCurrent().Name;

            // comparison between current user name and actually authenticated user is needed since some requests end with different values!
            if (_CurrentUser == null || !_CurrentUser.Username.Equals(currUsername))
            {
                _CurrentUser = _ScopedDataAccess.AppUserRepository.AllNoTracking
                    // some includes
                    .SingleOrDefault(u => u.IsEnabled && u.Username.Equals(currUsername));

                if (_CurrentUser == null)
                {
                    logger.LogEx(LogLevel.Info, "GetLoggedUserData -  user {0} authentication failed", currUsername);
                    return null;
                }
            }

            return _CurrentUser;
        }
    }

我的问题是,即使SecurityService每个请求都实例化,有时我会收到一个_CurrentUser.Username不同的实例currUsername(即两者都是我执行测试的有效 A/D 用户)。

当前的解决方法是必须!_CurrentUser.Username.Equals(currUsername)使缓存的用户实例无效,如果请求身份验证的用户与缓存的用户不同,但我想知道发生了什么。

只是出于好奇,我检查InThreadScope并遇到了同样的问题,但我认为这可以通过 IIS 使用的线程池可能为另一个请求提供相同的线程这一事实来解释。

有谁知道为什么 InRequestScope 会这样?

谢谢。

[编辑]

当前用户与缓存用户不同时调用堆栈:

ProjectName.Models.dll!ProjectName.Models.SecurityService.GetLoggedUserData() 第 54 行 C# ProjectName.Models.dll!ProjectName.Models.SecurityService.GetAndCheckUserData() 第 76 行 C# ProjectName.Models.dll!ProjectName.Models.SecurityService.IsAdmin。 get() 第 98 行 C# ProjectName.Models.dll!ProjectName.Models.EntitiesCache.ProjectStatuses.get() 第 51 行 C# ProjectName.Services.dll!ProjectName.Services.ProjectService.CreateSelectorsDomain() 第 253 行 C# ProjectName.Services.dll! ProjectName.Services.ProjectService.ProjectService(ProjectName.Models.ISecurityService securityService, ProjectName.Models.IEntitiesCache entityCache, ProjectName.Models.IScopedDataAccess dataAccess, ProjectName.Services.IProjectTemplateService projectTemplateService) 第 33 行 C# [外部代码] ProjectName.Web.dll!ProjectName .Web。NinjectWebCommon.PerformInjectionOn(object instance) Line 93 C# ProjectName.Web.dll!ProjectName.Web.BaseController.BaseController() Line 21 C# [外部代码]

同步中所有步骤的逻辑 (no async, await, no Tasks)

4

0 回答 0