2013-09-06 2 views
3

ASP.NET MVC 응용 프로그램에서 내 컨트롤러에서 "Services"메서드를 호출합니다.IoC - 필요할 때까지 컨트롤러에서 서비스 초기화 지연

일반적으로 ReportingController 컨트롤러는 ReportingServices에서 메소드를 호출합니다. 서비스 클래스는 Mvc.IntegrationAutofac으로 인스턴스화됩니다.

builder.RegisterControllers(Assembly.GetExecutingAssembly()); 

서비스가 컨트롤러 생성자에 삽입됩니다.

public ReportingController(ReportingServices service) 

지금까지 그렇게 좋았습니다. 가끔 컨트롤러가 다른 서비스의 메서드를 호출해야합니다. 컨트롤러에 속성을

builder.RegisterControllers(Assembly.GetExecutingAssembly()) 
     .PropertiesAutowired(PropertyWiringOptions.PreserveSetValues); 

그리고 추가 : 나는 autofac 구성을 변경

public CommonServices CommonService { get; set; } // new properties 
public ReportingController(ReportingServices service) {} // existing ctor 

무엇 그러나 이제 어떻게하면 컨트롤러가 인스턴스화 될 때 모든 속성은 또한이 경우에도 설정되고 있다는 점이다 특정 ActionMethod에서는 사용되지 않습니다.

필자는 Autofac에게 필요한 때까지 속성의 인스턴스화를 지연 시키거나 단순히이 불필요한 초기화를 신경 쓰지 말라고 어떻게 말할 수 있습니까?

+0

컨트롤러에 너무 많은 책임이있을 수 있습니다. –

+0

'Lazy '을 사용하십시오 : http://stackoverflow.com/questions/3075260/what-happened-to-lazyt-support-in-autofac –

+0

@ ta.speot.is : 당신이 가지고있는 것이 좋은 습관이라는 것을 의미합니까? 컨트롤러와 서비스간에 1 대 1의 관계가 있습니까? 그리고 만약 컨트롤러가 갑자기 다른 서비스로부터 무언가를 필요로한다면 이것은 아마도 컨트롤러 자체가 아니라 서비스 자체에서 처리되어야 할 것입니다. 액세스하지 않을 때까지 – Laoujin

답변

1

autofac support Lazy<T>out of the box.

그래서 당신은 단지로 속성을 선언해야합니다

public Lazy<CommonServices> CommonService { get; set; } 

그리고 Autofac가 인스턴스화 할 것이다 CommonServices 당신이 CommonService.Value와 게으른의 값에 액세스하지 않습니다 때까지.

+0

...? – Alex

+0

@Alex Autofac은 여러분이 접근하지 않을 때까지'CommonServices'를 생성하지 않을 것입니다. 그래서이 예제에서 :'CommonService'의'Value' 속성. 그래서'CommonService.Value'를 쓰지 않으면 Autofac 당신의'CommonServices'를 만들지 않을 것입니다. – nemesv

관련 문제