var builder = new ContainerBuilder(); builder.RegisterModule<AttributedMetadataModule>(); builder.RegisterModule(new ConfigurationSettingsReader()); //如果是多个dll含有,要调用多次 builder.RegisterControllers(typeof(MvcApplication).Assembly) .PropertiesAutowired() //注入到属性 .InstancePerHttpRequest(); builder.RegisterSource(new ViewRegistrationSource()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
在Global.asax.cs的Application_Start加入这段,我是习惯单独一个类里的一个方法做这个,然后被Application_Start调用
public class LeaveController : Controller { private readonly IComponentContext _icoContext; private Lazy<ITest> Test { get; set; } public LeaveController(Lazy<ITest> test,IComponentContext icoContext) { _icoContext = icoContext; this.Test = test; } /// <summary> /// 用IComponentContext 来获得,显式调用Resolve /// </summary> /// <returns></returns> public ActionResult ContextIndex() { var test2 = _icoContext.Resolve<ITest>(); return View("Index", "", test2.Test()); } /// <summary> /// 用ApplicationContainer 来获得,显式调用Resolve /// </summary> /// <returns></returns> public ActionResult ApplicationIndex() { var test3 = AutofacDependencyResolver.Current.ApplicationContainer.Resolve<ITest>(); return View("Index", "", test3.Test()); } /// <summary> /// 用构造函数的Lazy加载 /// </summary> /// <returns></returns> public ActionResult Index() { return View("Index", "", this.Test.Value.Test()); } }
用构造函数注入的比较常见,IComponentContext和
AutofacDependencyResolver.Current.ApplicationContainer另外做法