Through the first two parts of learning, the acquisition of objects has been very simple, the previous use of the object to obtain the method to sum up, but also has not been used to supplement the method.
The method of getting an object in the Unity container also includes the generic method and the non-generic overload corresponding to it, where only the generic method is described.
Get an object from a type
We use the method resolve<t> () to get the object based on the type. This method is the most used in the first two parts to get the object of the registered default type mapping. The sample code looks like this:
Get objects based on type and name
Use method resolve<t> (string name) here to get the object based on the type and name. This method is used to obtain an object that has a named type mapping registered. The sample code looks like this:
Gets all objects of the specified type
To get all the objects of a specified type, we can use the resolveall<t> () method in Unity. This is useful, for example, when getting all the plug-ins that are registered in the system.
Note: This method only gets the object of the named type Registration mapping.
The sample code is as follows:
To inject dependency into an existing object
In the real world, we often have no control over the creation of certain objects, such as ASP.net pages, but we need to inject dependencies into these objects. In this case, we can use the buildup<t> (T existing) method to apply the dependency of the specified type.
We use an easy way to simulate this:
From the above code we can see that if Tel is created outside the method, by using the BuildUp method, the dependency is automatically applied to the Tel object.
Note: The BuildUp method can only be applied to attribute injection and method invocation injection because it does not execute the constructor of the requested object.
Summary
In this paper, we briefly describe several methods of object acquisition, and we can see that the acquisition of objects is very simple after registering type mappings using the Unity container.
This article supporting source code