在 ASP.NET MVC应用程序中,我从控制器调用"服务"方法。
通常,名为 ReportingController
的控制器会调用 ReportingServices
的方法。服务类正在实例化,Autofac
与Mvc.Integration
.
builder.RegisterControllers(Assembly.GetExecutingAssembly());
然后将服务注入到控制器构造函数中。
public ReportingController(ReportingServices service)
目前为止,一切都好。但有时,控制器需要从其他服务调用方法。我更改了自动fac配置:
builder.RegisterControllers(Assembly.GetExecutingAssembly())
.PropertiesAutowired(PropertyWiringOptions.PreserveSetValues);
并向控制器添加了属性:
public CommonServices CommonService { get; set; } // new properties
public ReportingController(ReportingServices service) {} // existing ctor
但是,现在发生的情况是,当控制器实例化时,所有属性也会被设置,即使它们从未被特定的 ActionMethod 使用过。
我如何告诉 Autofac 延迟属性的实例化,直到需要为止,或者我根本不应该关心这种不必要的初始化?
Autofac支持开箱即用的Lazy<T>
。
因此,您只需要将属性声明为:
public Lazy<CommonServices> CommonService { get; set; }
Autofac不会实例化您的CommonServices
,直到您不通过CommonService.Value
访问Lazy的值。