MVC /团结 - 如何把依赖注入定制FilterAttributes? [英] MVC/Unity - How to inject dependencies into custom FilterAttributes?

查看:199
本文介绍了MVC /团结 - 如何把依赖注入定制FilterAttributes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义 HandleErrorAttribute 扩展 FilterAttribute

我怎么能有团结在它注入控制器的依赖本身?

How can I have Unity inject dependencies into this attribute at the same time that it injects the controller's dependencies itself?

推荐答案

好了,想通了。

主要是我用本的解决方案,从上面的博客文章,他指出。

Mostly I used Ben's solution above from the blog post he pointed to.

问题是,统一的行为方式略有不同。

The problem is that Unity behaves a little differently.

您不能在过滤器注入依赖直接的,因为它们分别是类型IActionFilter和个IExceptionFilter的。这使我相信他们是只读的,这其实并非如此。只是,团结需要知道,以注入明确的类型。

You can't inject dependencies on the filters directly, because they are of type IActionFilter and IExceptionFilter respectively. This led me to believe they were readonly, which isn't so. It's just that Unity needs to know the explicit type in order to inject.

所以,在本文所提供的覆盖的方法,统一的用户需要查询的问题的类型的过滤器,然后建立他们。

So, in the overridden method provided by the article, Unity users need to query the filters for the types in question, and then build them up.

public UnityActionInvoker(IUnityContainer container, IList<Type> typesToInject)
        {
            _container = container;
            _typesToInject = typesToInject;
        }

然后在重写的方法,做这样的事情:

And then in the overridden method, do something like this:

  var needsInjection = filters.Where(filter => typesToInject.Contains(filter.GetType()));

一个有点乱,但它只需要进行一次,并保留一切去耦,本建议。

A bit messy, but it only needs to be done once, and keeps everything decoupled as Ben suggests.

其他疑难杂症的是,你不能调用_container.BuildUp(过滤器)foreach循环里面,因为过滤器是只读的在这方面。

The other gotcha is that you can't call _container.BuildUp(filter) inside a foreach loop, because the filter is readonly in that context.

这篇关于MVC /团结 - 如何把依赖注入定制FilterAttributes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆