c# - Ninject 和 MVC3 : Dependency injection to action filters

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

关于如何使用 Ninject 在 ASP.NET MVC3 中的 ActionFilter 上进行属性注入(inject),我发现了大量不确定的文章和问题。

谁能给我一个明确的例子吗?

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

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));
    }

  }
}

我的服务和助手从未被注入(inject)。我需要更改什么?

最佳答案

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

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/

关于c# - Ninject 和 MVC3 : Dependency injection to action filters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5078046/

相关文章:

asp.net-mvc-3 - 在 ASP.NET MVC 中编译 View 是一个好的实践吗?

c# - Ninject 注入(inject)接口(interface)的多重绑定(bind)

dependency-injection - Ninject:使用哪种注入(inject)模式来注入(inject)多个依赖项?

c# - 如何使用 Ninject 扫描通用类型的所有实现

c# - MailMessage Bcc AddRange 的扩展方法

C# 将列表中所有项目的字段设置为相同的值

c# - 使用 CSOM C# 创建网站集时出现错误值不能为空。参数名称 : source

Ajax json 跨域发布到 Controller , "not allowed by"Access-Control-Allow-Headers

c# - 是否有不依赖于 IDisposable 的 Using 模式?

c# - 使用 Ajax.ActionLink 将数据传递给 Controller