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 속성에 setter를 추가하여 쓰기 가능하도록 할 수 있습니까? 생성자에서 매개 변수로 ICustomService를 추가 하시겠습니까? –

+1

[ASP.Net Core (MVC 6) - Action Filter에 서비스 삽입]의 가능한 복제본] (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?

관련 문제