使用Spring.Net注入依赖关系ASP.NET MVC ActionFilters [英] Using Spring.Net to inject dependencies into ASP.NET MVC ActionFilters
问题描述
我使用MvcContrib做我的Spring.Net ASP.Net MVC控制器依赖注入。
我的依赖性没有被注入到我的CustomAttribute行为过滤器。
如何让我的依赖关系呢?
假设你有一个看起来像这样的ActionFilter:
公共类CustomAttribute:ActionFilterAttribute,ICustomAttribute
{
私人IAwesomeService awesomeService; 公共CustomAttribute(){} 公共CustomAttribute(IAwesomeService awesomeService)
{
this.awesomeService = awesomeService;
} 公共覆盖无效OnActionExecuting(ActionExecutingContext filterContext)
{
//做一些工作
}
}
随着Spring.Net配置部分看起来像这样:
<对象ID =CustomAttributeTYPE =Assembly.CustomAttribute,集结号单身=false的>
<构造 - 精氨酸REF =AwesomeService/>
< /对象>
和使用属性,像这样:
[自定义]
公共FooController的:控制器
{
//做一些工作
}
在这里艰难的部分是ActionFilters似乎得到新的实例化的每个请求,并在背景下,是春天的地方是知道外面。我用我的ActionFilter构造的春天ContextRegistry类处理相同的情况。不幸的是它引入了春天特定API的使用到code,这是一个很好的做法,以避免,如果可能的话。
下面就是我的构造函数如下:
公共MyAttribute()
{
CustomHelper = ContextRegistry.GetContext()GetObject的(CustomHelper)作为IConfigHelper。
}
请记住,如果要加载多个Spring上下文的,你需要指定你在的getContext(...)方法想要的内容。
I'm using MvcContrib to do my Spring.Net ASP.Net MVC controller dependency injection. My dependencies are not being injected into my CustomAttribute action filter. How to I get my dependencies into it?
Say you have an ActionFilter that looks like so:
public class CustomAttribute : ActionFilterAttribute, ICustomAttribute
{
private IAwesomeService awesomeService;
public CustomAttribute(){}
public CustomAttribute(IAwesomeService awesomeService)
{
this.awesomeService= awesomeService;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Do some work
}
}
With a Spring.Net configuration section that looks like so:
<object id="CustomAttribute " type="Assembly.CustomAttribute , Assembly" singleton="false">
<constructor-arg ref="AwesomeService"/>
</object>
And you use the Attribute like so:
[Custom]
public FooController : Controller
{
//Do some work
}
The tough part here is that ActionFilters seem to get instantiated new with each request and in a context that is outside of where Spring is aware. I handled the same situations using the Spring "ContextRegistry" class in my ActionFilter constructor. Unfortunately it introduces Spring specific API usage into your code, which is a good practice to avoid, if possible.
Here's what my constructor looks like:
public MyAttribute()
{
CustomHelper = ContextRegistry.GetContext().GetObject("CustomHelper") as IConfigHelper;
}
Keep in mind that if you are loading multiple Spring contexts, you will need to specify which context you want in the GetContext(...) method.
这篇关于使用Spring.Net注入依赖关系ASP.NET MVC ActionFilters的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!