Unity Application Block 1.0 series (6): prevents circular references

Source: Internet
Author: User

In IntroductionConstructor Injection,Property InjectionAndMethod call InjectionIt is particularly mentioned that circular references (Circular references) should not appear, because it is difficult to detect such problems. The best solution is to writeCodeAvoid this situation whenever possible.

Let's take a look at several scenarios of circular references. We should try to avoid this situation when using the dependency injection framework:

1. The objects generated through constructor injection reference each other in the parameters of the constructor.

Public   Class Class1
{
Public Class1 (class2 Test2)
{
..
}
}

Public ClassClass2
{
PublicClass2 (class1 test1)
{

}
}

Constructor injection is implemented when class1 is loaded through the Unity container. Because class1 depends on class2, class2 is loaded first. Constructor injection will also be performed when class2 is loaded. Because class2 is dependent on class1, class1 ...... in this way, continuous loading becomes an endless loop and cannot be jumped out.

2. The object generated through constructor injection serves as the parameter of the constructor.

Let's look at the example:

Public   Class Class1
{
Public Class1 (class1 test1)
{}
}

3. Mutual reference of objects generated through method call Injection

Let's look at the example:

Public   Class Class1
{
[Injectionmethod]
Public   Void Method1 ()
{
Method2 ();
}

[Injectionmethod]
Public VoidMethod2 ()
{
Method1 ();
}
}

4. objects generated through property (setter) injection reference each other

Let's look at the example:

Public   Class Class1
{
[Dependency]
Public   String Propert1
{
Get
{
Return Propert2;
}
}

[Dependency]
Public StringPropert2
{
Get
{
ReturnPropert1;
}
}
}

By: inrie (Hong Xiaojun)
Source:Http://www.cnblogs.com/inrie

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.