2017-02-21 47 views
0

我使用: 行动过滤器 - 依赖注入

using Microsoft.Extensions.DependencyInjection; 

当我尝试创建新ActionFilter我需要访问其他服务,所以我尽量写的标准构造函数注入,但是当我costructor有参数我写类似的东西:

[OAuthFilter(serviceToInject)] 

我不能给becouse行动过滤器不能有这样的参数。

我该怎么办?动作过滤器不能有注入构造函数?通过依赖注入

[TypeFilter(typeof(OAuthFilter))] 
public class HomeController : Controller 
{ 
} 

这将实例化您的过滤器,并得到任何必要的组件:

+0

可能重复的:https://stackoverflow.com/questions/29915192/property-注入属性 – Steven

+0

@Steven是用于ASP.NET MVC或ASP.NET 4,这是ASP.NET Core –

+0

@CamiloTerevinto:答案仍然相同:使您的属性为[passive](http:// blog.ploeh.dk/2014/06/13/passive-attributes/)或[Humble objects](http://xunitpatterns.com/Humble%20Object.html)。 – Steven

回答

1

可以使用TypeFilterAttribute。另一种选择是ServiceFilterAttribute

[ServiceFilter(typeof(OAuthFilter))] 
public class HomeController : Controller 
{ 
} 

但是这需要您在过滤器添加到服务宝典:

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddTransient<OAuthFilter>(); 
}