Ninject Property Injection无法处理ActionFilters

时间:2013-04-11 08:16:48

标签: asp.net-mvc dependency-injection ninject

我有一个接口和一个实现该接口的类

public interface ISessionVariables
{
    bool IsSessionTokenValidated { get; set; }
}

public class HttpContextSessionVariablesAdapter : ISessionVariables
{
    private T Get<T>(string key)
    {
        return (T)HttpContext.Current.Session[key];
    }

    private void Set(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }

    public bool IsSessionTokenValidated
    {
        get { return Get<bool>("IsSessionTokenValidated"); }
        set { Set("IsSessionTokenValidated", value); }
    }
}

我使用Ninject将接口绑定到实现:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ISessionVariables>().To<HttpContextSessionVariablesAdapter>();
}

我有一个ActionFilter

public class ValidateSessionTokenAttribute : ActionFilterAttribute
{
    [Inject]
    public ISessionVariables SessionVariables { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (SessionVariables.IsSessionTokenValidated == false)
        {
            throw new HttpException((int)HttpStatusCode.Unauthorized, "User session has expired");
        }

        base.OnActionExecuting(filterContext);
    }
}

奇怪的错误:

如果我将ValidateSessionTokenAttribute添加到ActionResult,则会填充SessionVariables属性。

[ValidateSessionToken]
public ActionResult Index()
{

}

如果我将相同的过滤器绑定到所有ActionResults,(在FilterConfig中),SessionVariables属性始终为null

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ValidateSessionTokenAttribute());
    }
}

我做错了什么?

0 个答案:

没有答案