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

How to implement dependency injection in ASP.NET MVC

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces ASP.NET MVC how to achieve dependency injection, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Preface

There is an automatic injection function in java's spring, which makes the code more concise and flexible, so I want to transplant this function to c #, and then analyze the implementation process step by step

1. Scene analysis using automatic injection

In asp.net mvc, no matter what the logical layering of the code is, the final presentation layer is the Controller layer, so our injection point is in Controller, where we need to replace the default ControllerFactory, scan the code to mark the objects to be injected, and instantiate the injection.

Public class FastControllerFactory: DefaultControllerFactory {public override IController CreateController (RequestContext requestContext, string controllerName) {Type type = this.GetControllerType (requestContext, controllerName); Object obj = GetControllerInstance (requestContext, type); / / automatic injection of tag AutoWired attributes in Controller List AutoWiredFieldList = type.GetRuntimeFields (). Where (f = > f.GetCustomAttribute (typeof (AutoWired))! = null). ToList (); foreach (FieldInfo field in AutoWiredFieldList) {field.SetValue (obj, InjectUtil.Container.Resolve (field.FieldType)) } return obj as IController;}}

FastControllerFactory is a Controller factory we customized. Override the CreateController method to take the instance from the Bean container for assignment to the variable marked with AutoWired as a custom annotation. At the same time, we also need to replace the default factory in the Start method in the Global file.

ControllerBuilder.Current.SetControllerFactory (new FastControllerFactory ()); implementation of 2.IOC container

The custom containers in C # have many mature open source frameworks, such as AutoFac. Here we implement a lightweight version ourselves.

Source code address: https://gitee.com/grassprogramming/FastIOC

Let's focus on how to use asp.net mvc. First, we need to tag the Bean object that needs to be injected. This tag is called Component.

In the Start method in the asp.net mvc Global file, we need to add the Bean that needs to be automatically injected throughout the project into the container

Public class InjectUtil {public static ContainerBuilder Container; public static void Init () {Container = new ContainerBuilder (); / / get all assemblies var assemblies = System.Web.Compilation.BuildManager.GetReferencedAssemblies (). Cast (). ToArray (); / / inject all Component components Container.RegisterAssemblyTypes (assemblies, typeof (Component), true); Container.Build ();}}

At this point, the Controller level is done, and then you need to further deal with it in the initialization Bean instance method in the IOC container.

Private Object GetInstance (RegisterEntity Entity) {Object obj = null; if (Entity.IsEnableIntercept) {bool IsExtend = Entity.RealType = = Entity.RegistType; obj = DynamictProxy.CreateProxyObject (Entity.RealType, Entity.RegistType, Entity.InterceptType, IsExtend, Entity.IsInterceptAllMethod);} else {var constructors = Entity.RegistType.GetConstructors (); obj = constructors [0] .invoke (new Object [] {}) } / / here the singleton mode is used to instantiate Instance storage, exposing in advance the object instance if (! SingleInstanceDic.ContainsKey (Entity.RealType)) {SingleInstanceDic.Add (Entity.RealType, obj) that has not been subsequently set. } / / if the class is marked with Component and there is a Field marked with AutoWired, automatic injection of if (Entity.RealType.GetCustomAttribute (typeof (Component), true)! = null) {/ / GetRuntimeFields is used here. This method returns all fields defined on the specified type, including inherited, non-public, instance, and static fields. Foreach (FieldInfo Field in Entity.RealType.GetRuntimeFields ()) {if (Field.GetCustomAttribute (typeof (AutoWired), true)! = null) {Type FieldType = Field.FieldType If (Contains (FieldType)) {/ / determines whether it is included in singleton storage. If so, take out the assignment. Here, you can prevent the endless loop if (SingleInstanceDic.ContainsKey (FieldType)) {Field.SetValue (obj, SingleInstanceDic [FieldType]) caused by circular dependency. } else {Field.SetValue (obj, Resolve (FieldType));}} return obj;}

The GetInstance method is the core method for instantiating Bean objects. In fact, it is very simple to create objects through reflection. There are two points to pay attention to.

1) for a Bean initialization, all variables in the Bean need to be scanned. If there are nested objects with dependency injection inside, recursion is required until there is no Field to be injected.

2) I use singleton pattern here, because in the course of testing, there may be dependency injection of B in class An and dependency injection of An in class B. in the normal creation process, if recursion is used for scanning, it will enter an endless loop and memory overflow, so the singleton of an object is put into the dictionary once it is created, and if the object is scanned again, it needs to be injected directly. Circular references are avoided.

3. Other

If you need dependency injection for other classes that are not used in Controller, you need to extract and use them directly from the Bean container of IOC.

Private AuthUtil @ AuthUtil = InjectUtil.Container.Resolve (); Thank you for reading this article carefully. I hope the article "how to achieve dependency injection in ASP.NET MVC" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and follow the industry information channel. More related knowledge is waiting for you to learn!

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

Development

Wechat

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

12
Report