2

試圖尋找,但沒有具體的答案(我很新在此)Spring.NET DI注射...如何做動作過濾器(ASP.NET MVC 3)

使用Spring.NET支持ASP。 NET MVC 3,如何在動作過濾器中執行依賴注入?研究過,但我根本不知道! :/

在Spring.NET紀錄片上,它似乎提到這一切都已經被處理,所需做的只是將動作過濾器註冊到spring的上下文中,並且spring將處理所有必要的注入處理。

http://www.springframework.net/doc-latest/reference/html/web-mvc3.html

不過,我只是無法得到它的工作。圍繞學習和博客等,在使用過濾器供應商,或直接使用ContextRegistry.GetContext()的提及,但是這似乎並沒有堅持AOP ..

Using Spring.Net to inject dependencies into ASP.NET MVC ActionFilters

Spring.Net & Attribute Injection

所以什麼是這樣做的正確方法?我認爲這已經被spring.net覆蓋了,但它似乎並不是。

我到Spring.Web.Mvc3 v4.0.30319引用的,而我在ASP.NET MVC 3運行

編輯:

我嘗試這樣做:

SpringMvcDependencyResolver dr = 
     new SpringMvcDependencyResolver(ContextRegistry.GetContext()); 

然後通過dr.GetService<ITestService>();獲得服務這似乎使它有點工作,但不是獲得正確的實際服務實現(在我的Filters.xml中,我寫了屬性ref爲TestService),它返回th e服務的存根版本。我做錯了嗎?或者我必須篩選並通過GetServices()選擇合適的人或某物?

EDIT2:

@Andreas:很抱歉這麼晚纔回復。但是,我Global.asax確實有它

public class MvcApplication : Spring.Web.Mvc.SpringMvcApplication

爲了測試,我有這個在我的Spring配置:

<object type="Spring.Mvc3QuickStart.Filters.TestFilter, Spring.Mvc3QuickStart" singleton="false" > 
    <property name="Message" value="This is the ActionFilter message" /> 
</object> 

在我的過濾器:

public class TestFilter : ActionFilterAttribute 
{ 
    public string Message { get; set; } 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     filterContext.Controller.ViewBag.ActionMessage = Message; 
     base.OnActionExecuting(filterContext); 
    } 
} 

在我的控制器我有這個:

ViewData["Message"] = Message;

純粹爲了這個測試項目,過濾器應該注入消息。但產出並不如預期。

+0

任何幫助嗎? :) – RicL

+0

你可以請發佈你的彈簧配置的相關部分?當你從SpringMvcApplication派生你的global.asax時,prop注入動作過濾器可以工作。 – Andreas

+0

@安德里亞斯:編輯回答你的問題:) 嗯..不完全確定我的編輯與文本正確匹配,似乎他們沒有很好地顯示。 – RicL

回答

1

Spring.Net.Mvc3接縫的1.3.2版本是有點bug。在SpringMvcDependencyResolver方法public IEnumerable<object> GetServices(Type serviceType)將始終失敗。它應該是return services.Values.Cast<object>();而不是return services.Cast<object>();。最簡單的解決方法是覆蓋BuildDependencyResolverSpringMvcApplication並註冊您自己的固定SpringMvcDependencyResolver

我在這裏創造託管的完整解決方案: https://gist.github.com/1262927

+1

你有沒有報告這個錯誤並修復?我認爲,這將會受到歡迎。 Spring.net現在在github上託管。 – Marijn

+0

@ Marijn:案件是[SPRNET-1473](https://jira.springsource.org/browse/SPRNET-1473)。 – Andreas

+0

@Andreas,這是否意味着我仍然需要使用GetServices並通過IEnumerable進行篩選?嗯,我迷惑自己大聲笑。 我可以問一下,你能否提供一個這樣的工作樣本?沒有真正能夠讓IApplicationContext和ContextRegistry通過覆蓋工作..我可能會缺少某種形式的引用。 – RicL