Ninject和MVC3:依赖注入到动作过滤器

时间:2011-02-22 12:23:14

标签: c# asp.net-mvc-3 ninject webactivator

我发现了很多关于如何使用Ninject在ASP.NET MVC3中对ActionFilter进行属性注入的不确定文章和问题。

有人可以给我一个明确的例子吗?

这是我的自定义身份验证属性。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    [Inject]
    public IService Service { get; set; }

    [Inject]
    public IAuthenticationHelper AuthenticationHelper { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
         //My custom code
    }
 }

我正在使用WebActivator设置Ninject

[assembly: WebActivator.PreApplicationStartMethod(typeof(MyProject.Web.AppStart_NinjectMvc3), "Start")]

 namespace MyProject.Web {

   public static class AppStart_NinjectMvc3 {
        public static void RegisterServices(IKernel kernel) {

           //Binding things
    }

    public static void Start() {
        // Create Ninject DI Kernel 
        IKernel kernel = new StandardKernel();

        // Register services with our Ninject DI Container
        RegisterServices(kernel);

        // Tell ASP.NET MVC 3 to use our Ninject DI Container 
        DependencyResolver.SetResolver(new NinjectServiceLocator(kernel));
    }

  }
}

我的服务和助手永远不会注入。我需要改变什么?

2 个答案:

答案 0 :(得分:14)

在我看来,有一个比使用过滤器属性更好的解决方案。请参阅我的博客文章,了解使用Ninject声明过滤器的另一种方法。它不需要属性注入,而是使用构造函数注入:

http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/ http://www.planetgeek.ch/2011/02/22/ninject-mvc3-and-ninject-web-mvc3-merged-to-one-package/

答案 1 :(得分:8)

以下是您可以继续的方式:

public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication
{
    private class MyModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IService>().To<ServiceImpl>();
            Bind<IAuthenticationHelper>().To<AuthenticationHelperImpl>();
        }
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[] {
            new MyModule()
        };
        var kernel = new StandardKernel(modules);
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
        return kernel;        
    }
}

然后您可以拥有自定义授权属性:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    [Inject]
    public IService Service { get; set; }

    [Inject]
    public IAuthenticationHelper AuthenticationHelper { get; set; }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
    }
}

以及用它装饰的控制器动作:

[CustomAuthorize]
public ActionResult Index()
{
    return View();
}

并且应该注入依赖项。