本文介绍了是否有可能使用依赖注入/国际奥委会的ASP.NET MVC FilterAttribute?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的自定义 FilterAttribute 我用各种装饰 ActionMethods

I've got a simple custom FilterAttribute which I use decorate various ActionMethods.

如:

[AcceptVerbs(HttpVerbs.Get)]
[MyCustomFilter]
public ActionResult Bar(...)
{ ... }

现在,我想一些日志记录添加到这个CustomFilter行动..所以是个好孩子,我使用 DI /国际奥委会 ...,因此希望使用此模式为我定制的 FilterAttribute

Now, I wish to add some logging to this CustomFilter Action .. so being a good boy, I'm using DI/IoC ... and as such wish to use this pattern for my custom FilterAttribute.

所以,如果我有以下...

So if i have the following...

ILoggingService

和希望添加这个我自定义的 FilterAttribute ..我不知道怎么样。一样,它很容易为​​我做以下...

and wish to add this my custom FilterAttribute .. i'm not sure how. Like, it's easy for me to do the following...

public class MyCustomFilterAttribute : FilterAttribute
{
    public MyCustomFilterAttribute(ILoggingService loggingService)
    { ... }
}

但是,编译器错误说其装饰的属性我 ActionMethod (以上所列...)的需要1 ARG ..所以我只是不知道该怎么做:(

But the compiler errors saying the attribute which decorates my ActionMethod (listed above...) requires 1 arg .. so i'm just not sure what to do :(

推荐答案

我有物业注射工作和。

只要你有从Ninject.Web.MVC控制器工厂,这是相当简单的。

As long as you've got the controller factory from Ninject.Web.MVC, it's rather simple.

例如

public class EventExistsAttribute : FilterAttribute, IActionFilter
{
    [Inject]
    public IEventRepository EventRepo { private get; set; }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //Do stuff
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        //Do something else if you so wish...
    }
}

它基本上有一个隐藏的依赖,这样说缺点......但没有什么可以做这一点。

It has the drawback of essentially having a 'hidden' dependency, so to say... but there ain't much you can do about that.

HTHS,结果
查尔斯

HTHs,
Charles

这篇关于是否有可能使用依赖注入/国际奥委会的ASP.NET MVC FilterAttribute?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 10:18