Подтвердить что ты не робот

Ninject и MVC3: фильтры впрыскивания зависимостей к действию

Я нашел множество неубедительных статей и вопросов о том, как сделать инъекцию свойств в ActionFilter в ASP.NET MVC3 с помощью Ninject.

Может ли кто-нибудь дать мне ясный пример?

Здесь мой пользовательский атрибут auth.

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

  }
}

Мой сервис и помощник никогда не вводятся. Что мне нужно изменить?

4b9b3361

Ответ 1

Здесь вы можете продолжить:

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

и тогда у вас может быть свой собственный атрибут authorize:

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

и должны быть введены зависимости.

Ответ 2

По моему мнению, есть лучшее решение, чем использование атрибутов фильтра. См. Мои blogposts об альтернативном способе объявления фильтров с помощью 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/