2016-08-31 2 views
7

私は自分のASP.NET COREアプリケーションではどこでも、コンストラクタベースの依存性注入を使用して、私はまた私のアクションフィルタで依存関係を解決する必要があります:私はICustomServiceを置く場合ASP.NET COREで依存フィルタを使用したアクションフィルタの使用方法

[MyAttribute(Limit = 10)] 
public IActionResult() 
{ 
    ... 

その後
public class MyAttribute : ActionFilterAttribute 
{ 
    public int Limit { get; set; } // some custom parameters passed from Action 
    private ICustomService CustomService { get; } // this must be resolved 

    public MyAttribute() 
    { 
    } 

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 
    { 
     // my code 
     ... 

     await next(); 
    } 
} 

コントローラに私のプロジェクトをコンパイルできません。だから、アクションフィルタでインターフェースインスタンスを取得するために私はどのようにsupossedしますか?

+0

プロパティCustomServiceにセッターを追加して書き込み可能にすることはできますか?コンストラクタのパラメータとしてICustomServiceを追加しますか? –

+1

[ASP.Net Core(MVC 6) - アクションフィルタにサービスを注入]の可能な複製](http://stackoverflow.com/questions/36109052/asp-net-core-mvc-6-inject-service-into-action -filter) – gilmishal

+0

[asp.net?]のアクションフィルタにパラメータを追加するにはどうすればいいですか?(http://stackoverflow.com/questions/39181390/how-do-i-add-a-parameter-to -an-action-filter-in-asp-net) –

答えて

8

サービスロケータパターンを避けたい場合は、TypeFilterのコンストラクタインジェクションでDIを使用できます。

お使いのコントローラの使用では

[TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})] 
public IActionResult() NiceAction 
{ 
    ... 
} 

そして、あなたのActionFilterAttributeはもうサービスプロバイダインスタンスにアクセスする必要はありません。私にとって

public class MyActionFilterAttribute : ActionFilterAttribute 
{ 
    public int Limit { get; set; } // some custom parameters passed from Action 
    private ICustomService CustomService { get; } // this must be resolved 

    public MyActionFilterAttribute(ICustomService service, int limit) 
    { 
     CustomService = service; 
     Limit = limit; 
    } 

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 
    { 
     await next(); 
    } 
} 

注釈[TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})]は厄介であるように思われます。 [MyActionFilter(Limit = 10)]のような読みやすいアノテーションを取得するには、フィルタがTypeFilterAttributeから継承されている必要があります。私の答えはHow do I add a parameter to an action filter in asp.net?で、このアプローチの例を示しています。

+0

非同期が必要な場合は、 'IActionFilter'の代わりに' IAsyncActionFilter'を使うこともできます –

1

あなたはService Locatorを使用することができます。

public void OnActionExecuting(ActionExecutingContext actionContext) 
{ 
    var service = actionContext.HttpContext.RequestServices.GetService<IService>(); 
} 

あなたはコンストラクタ・インジェクションの使用TypeFilterを使用したい場合。 How do I add a parameter to an action filter in asp.net?

関連する問題