3

In an ASP.NET MVC application, I'm calling "Services" methods from my controllers.

Usually, a controller named ReportingController calls methods from ReportingServices. The service classes are being instantiated with Autofac with the Mvc.Integration.

builder.RegisterControllers(Assembly.GetExecutingAssembly());

The service is then injected into the controller constructor.

public ReportingController(ReportingServices service)

So far so good. But occasionally, a controller needs to call methods from other services. I changed the autofac configuration:

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

And added properties to the controllers:

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

What happens now however is that when the controller is instantiated, all properties are also being set, even if they are never used by a particular ActionMethod.

How can I tell Autofac to delay instantiation of the properties until required or perhaps I should simply not care about this unnecessary initialization?

Laoujin
  • 9,962
  • 7
  • 42
  • 69
  • Your controller may have too many responsibilities. – ta.speot.is Sep 06 '13 at 13:39
  • Use `Lazy`: http://stackoverflow.com/questions/3075260/what-happened-to-lazyt-support-in-autofac – ta.speot.is Sep 06 '13 at 13:40
  • @ta.speot.is: Do you mean that it is good practice to have pretty much a 1 on 1 relation between controllers and services? And that if a controller would suddenly need something from another service that this should perhaps be handled in the service itself and not in the controller? – Laoujin Sep 06 '13 at 13:47

1 Answers1

0

Autofac supports Lazy<T> out of the box.

So you just need to declare your property as:

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

And Autofac won't instantiate your CommonServices until you don't access your Lazy's value with CommonService.Value.

nemesv
  • 138,284
  • 16
  • 416
  • 359
  • until you don't access...? – Alex May 19 '14 at 13:48
  • @Alex Autofac won't create your `CommonServices` until you don't access it, so in the this example: the `Value` property of the `CommonService` so if you don't write `CommonService.Value` then Autofac won't create your `CommonServices` – nemesv May 19 '14 at 14:13