Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example sharing of manual and automatic injection of Autofac

2025-04-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you examples of manual and automatic injection of Autofac. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.

Private IGradeService _ gradeService; public HomeController (IGradeService gradeService) {_ gradeService = gradeService;} public ActionResult Index () {var model = _ gradeService.GetAllGrade () .ToList (); return View (model);}

Modify Global.asax by adding the following code to the Application_Start () method, paying attention to referencing Autofac, Autofac.Integration.Mvc, and other references

Var builder = new ContainerBuilder (); builder.RegisterType (). As (). InstancePerHttpRequest (); var container = builder.Build (); DependencyResolver.SetResolver (new AutofacDependencyResolver (container)); / / automatic injection of var baseType=tyeOf (Idependency); var assemblys=AppDomain.currentDomain.getAssemblies (). Tolist (); builder.RegisterAssemblyTypes (assemblys.ToArry ()) .where (t+baseTye.IsAssignableFrom (t) & & tasking baseType) .AsImplementedInterfaces () .InstancePerLifetimeScope ()

Note: DependencyResolver.SetResolver (new AutofacDependencyResolver (container)); this must be placed after builder.RegisterControllers (Assembly.GetExecutingAssembly ());, or there will be an error: no argument constructor is defined for the object.

The above is the example of manual and automatic injection of Autofac shared by Xiaobian. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report