Asp.net MVC的具有Ninject和Filter属性的依赖注入

Asp.net MVC的具有Ninject和Filter属性的依赖注入

我正在为asp.net mvc 3写一个自定义的授权过滤器。我需要向类中注入一个用户服务,但是我不知道该怎么做。


public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter

{

    private IUserService userService;

    private string[] roles;


    public AuthorizeAttribute(params string[] roles)

    {

        this.roles = roles;

    }


    public void OnAuthorization(AuthorizationContext filterContext)

    {

        throw new NotImplementedException();

    }

}

我正在使用ninject进行依赖项注入。我不想使用“工厂”或“服务定位器”模式。


我的绑定在global.acsx中看起来像这样:


    internal class SiteModule : NinjectModule

    {

        public override void Load()

        {

            Bind<IUserService>().To<UserService>();

        }

    }


大话西游666
浏览 503回答 4
4回答

米脂

如果要使用构造函数注入,则需要创建一个属性和一个过滤器。///marker attributepublic class MyAuthorizeAttribute : FilterAttribute { }//filterpublic class MyAuthorizeFilter : IAuthorizationFilter{&nbsp; &nbsp; &nbsp; private readonly IUserService _userService;&nbsp; &nbsp; &nbsp; public MyAuthorizeFilter(IUserService userService)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _userService = userService;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; public void OnAuthorization(AuthorizationContext filterContext)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var validUser = _userService.CheckIsValid();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!validUser)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "AccessDenied" }, { "controller", "Error" } });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }}捆绑:this.BindFilter<MyAuthorizeFilter>(System.Web.Mvc.FilterScope.Controller, 0).WhenControllerHas<MyAuthorizeAttribute>();控制器:[MyAuthorizeAttribute]public class YourController : Controller{}嗯...

动漫人物

我为Ninject无法处理构造的任何情况找到了一个简单的解决方案:var session = (IMyUserService)DependencyResolver.Current.GetService(typeof (IMyUserService));实际上,这正是我与自定义AuthorizeAttribute一起使用的内容。比必须实现单独的FilterAttribute容易得多。
打开App,查看更多内容
随时随地看视频慕课网APP