存储库不会从HttpContext.Current.User.IsInRole中注入

时间:2012-06-29 00:44:47

标签: asp.net-mvc-3 nhibernate fluent-nhibernate ninject roleprovider

我有一个带有自定义成员资格和角色提供程序的MVC应用程序。我正在检查用户是否处于这样的角色:

public static bool CustomersVisible
{
    get
    {
        return
            HttpContext.Current.User != null &&
            HttpContext.Current.User.Identity.IsAuthenticated &&
            HttpContext.Current.User.IsInRole("Admin");
    }
}

自定义角色提供程序如下所示:

public class DRRoleProvider : RoleProvider
{
    private IUserProfileRepository _userProfileRepository;
    private IRoleRepository _roleRepository;

    public DRRoleProvider() {}

    public DRRoleProvider(IUserProfileRepository userProfileRepository, IRoleRepository roleRepository)
    {
        _userProfileRepository = userProfileRepository;
        _roleRepository = roleRepository;
    }

. . .

public override bool IsUserInRole(string username, string roleName)
{
    var user = _userProfileRepository.GetByUserName(username);
    var role = _roleRepository.GetByName(roleName);

    if (user != null)
    {
        return user.Roles != null && user.Roles.Contains(role);
    }

    return false;
}

编辑添加:这是我的NinjectControllerFactory:

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory()
    {
        ninjectKernel = new StandardKernel();
        AddBindings();
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return controllerType == null
                   ? null
                   : (IController) ninjectKernel.Get(controllerType);
    }

    private void AddBindings()
    {
        ninjectKernel.Bind<ICustomerRepository>().To<CustomerRepository>();
        ninjectKernel.Bind<IUserProfileRepository>().To<UserProfileRepository>();
        ninjectKernel.Bind<IRoleRepository>().To<RoleRepository>();
        ninjectKernel.Bind<ISessionFactory>().ToProvider<SessionFactoryBuilder>().InSingletonScope();
        ninjectKernel.Bind<ISession>().ToMethod(CreateSession).InSingletonScope();

        ninjectKernel.Inject(Membership.Provider);
        ninjectKernel.Inject(Roles.Provider);
    }

    private ISession CreateSession(IContext context)
    {
        var session = context.Kernel.Get<ISessionFactory>().OpenSession();
        return session;
    }
}

当调用IsUserInRole方法时,我在_userProfileRepository上得到一个空引用异常。从HttpContext.Current.User.IsInRole调用时,如何确保注入存储库?从我自己的代码调用它时工作正常。

1 个答案:

答案 0 :(得分:1)

RoleProvider实际上不依赖于依赖注入。它要求您具有默认构造函数。请尝试使用属性注入。

由于您使用的是Ninject,这些问题/答案可能会有所帮助:
Ninject with MembershipProvider | RoleProvider
Custom Role Provider using DI ninject throwing error