Link: http://www.doriandeng.cn/archives/99.html
Through the learning of the first two parts, the object acquisition is very simple. Here, we will summarize the previously used object acquisition methods and supplement the methods that have not been used.
The methods for getting objects in the Unity container also include the generic method and the corresponding non-generic overload. Here, only the generic method is described.
Get objects by type
We use resolve <t> () to obtain Objects Based on the type. This method is used most frequently in the first two parts and is used to obtain registered default type ing objects. ExampleCodeAs follows:
Get object based on type and name
Here, we use resolve <t> (string name) to obtain the object based on the type and name. This method is used to obtain the object registered with the name type ing. The sample code is as follows:
Obtains all objects of the specified type.
To obtain all objects of the specified type, we can use the resolveall () method in unity. For example, it is very useful to obtain all the plug-ins registered in the system.
Note: This method can only obtain the object of the registration ing of the naming type.
The sample code is as follows:
Inject dependency into existing objects
In the real environment, we often cannot control the creation process of some objects, such as ASP. NET pages, but we already need to inject dependencies into these objects. In this case, we can use the buildup <t> (T existing) method to depend on the specified type of application.
We use a simple method to simulate this situation:
From the code above, we can see that if Tel is created outside the method, after the buildup method is used, the dependency will be automatically applied to the Tel object.
Note: The buildup method only applies to property injection and method call injection because it does not execute the constructor of the request object.
Summary
In this article, we briefly describe several methods for obtaining objects. We can see that after registering the type ing with the unity container, object acquisition is very simple.
Source codeDownload
Look-into-unity-1-1-resolveobject.zip
Hope to help you!
Deng Ming
Ideal & Beauty