AUTOFAC Comprehensive Analysis Series (version: 3.5) –[use (recommended): 4. Type association (service exposure)]

Source: Internet
Author: User

Objective
AUTOFAC

AUTOFAC is a set of efficient dependency injection frameworks.

AUTOFAC Official website: http://autofac.org/

AUTOFAC Open Source project on GitHub: HTTPS://GITHUB.COM/AUTOFAC/AUTOFAC

AUTOFAC installation: NuGet with VS is easy to get.

Type Association (service exposure)

About the "type Association (service exposure)" The name is derived from the official online exposes word, a little word is poor, I hope you can read the blog after reading to provide more appropriate description of the name.

The previous AUTOFAC series has always mentioned that the direct registration type is not the main use of AUTOFAC already relies on injection, the best dependency injection and the use of AUTOFAC, are combined with the concept of interface-oriented (abstract) programming. What we are advocating is to rely on abstraction rather than specificity, and I have a simple explanation in the final summary of the last blog post.

Knowing AUTOFAC's friends may feel awkward when they look at the front posts, because they don't use as<>. But bloggers feel that dependency injection is not necessarily associated with interfaces or abstract classes in order to count dependency injection, and bloggers are trying to separate dependency injection from abstract programming, and then combine it with the concept of abstract programming when you understand the concept of dependency injection, which may be easier for beginners to assimilate. The following blog instance code will also decide whether to use type affinity (service exposure) based on the actual situation, basics.

Type Association
As Association

There is really not much content about type affinity (service exposure), which is basically associated with as when we are doing manual correlation. Let's take a look at an example first:

classprogram{Static voidMain (string[] args) {        varBuilder =NewContainerbuilder (); Builder. Registertype<Class1> (). As<iinterface>(); varcontainer =Builder.        Build (); IInterface Inter= Container. Resolve<iinterface>(); Console.WriteLine (Inter.        ID); Console.Write ("Press any key to continue ...");    Console.readkey (); }}
Interface iinterface{    get;}} class class1:iinterface{    private  Guid _id;      Public Guid Id    {        getreturn  _id;}}    }

As you can see from the code, we add a as<...> () directly after the type registration, and then we are using the as type when we use resolve.

Let's review the previous usage, before the direct Registertype, the last registered type is Class1,resolve, and is also used directly with Class1. However, although the registration is still CLASS1, it is used IInterface, and the last instance type obtained is CLASS1. This is a bit of a detour, at the level of code, but we can also understand that the iinterface is registered, but the implementation is specified for IInterface. The advantage of this is that if we want to change the implementation of the iinterface, we only need to modify the registered code, without modifying the code to get the penalty and subsequent use of the IInterface instance.

As also has two overloads, one is a variable array of type and the other is a service variable array. The second way we generally do not, autofac the bottom of the use, the recommended article does not explain.

This is registered using Registertype, and similarly, other registration methods can be used for type association.

Multi-correlation

A class may implement multiple interfaces, and if we want to resolve more than one interface, what should we get? The easiest way to think about it is simply to register as once again. Well, that's true, but do you remember the way IEnumerable and IQueryable chained programming? AUTOFAC also has such an easy way, if you want multiple interfaces or types to be associated with the same type, we can continue to as:builder.registertype<c1> () directly after the expression. As<i1> (). As<i2> (). As<i3>, so,resolve<i1>, resolve<i2>, resolve<i3> get all the C1 type instances.

Self-correlating asself
As Use note

When you do not use as, Registertype registers what type to use, resolve uses what type to obtain, but after using as, only the type of as is used for resolve. As in the previous example, you can only resolve<iinterface>, and not resolve<class1>, or you will throw an exception.

But what if you want to be able to get Class1 without throwing an exception while resolve<class1>? In the case of not knowing the Asself method, you can as<class1> it directly at the time of registration; Another way is to asself:

// These two code effects are the same as builder. Registertype<class1> (). As<iinterface> (). As<class1>(); builder. Registertype<Class1> (). As<iinterface> (). Asself ();

Relatively speaking, no matter what type, the last just asself on the line, so the relative convenience, but the specific still depends on personal habits.

Batch Association Asimplementedinerfaces

Depending on the name of the method, we can probably guess what it does, Asimplementedinterfaces is the type association directly with the type implementation interface. For example, the following types are defined:

Interface I1 {} Interface I2 {} Interface I3 {} Interface I4 {} Interface I5 {} Interface I6 {} Interface I7 {} class c1:i1, I2, I3, I4, I5, I6, i7{}

A type implements 7 interfaces, and then we want to resolve any one of these seven, can get to the C1 instance, according to our first section of the Multi-association, the code can be abbreviated as:

Builder. Registertype<c1>()        . as <I1> (). As<i2>()        . as <I3> (). As<i4>()        . as <I5> (). As<i6>()        . as <I7> ();

Although this code is a lot more concise than registertype multiple times, it is still not concise enough, but after having the Asimplementinterfaces method, it can be very simple:

Builder. Registertype<c1> (). Asimplementedinterfaces ();

In assembly registration This way, Asimplementinterfaces is more powerful, assembly registration in this way, is the bulk register type, these types of bulk registration, they may have implemented a different interface, so that we have no way to their one by one interface, However, with the Asimplementinterfaces method, all registration types can be automatically associated with the implemented interface. Of course, because of this, you need to be aware when using asimplementinterfaces that you really want to associate with all interfaces.

Type Association note points
An interface/type can only be associated with one type

As we saw earlier, you can associate a type with multiple interfaces so that multiple interfaces resolve the result to be the same type instance. It is important to note that this is irreversible, that is, an interface cannot be associated with more than one type, because this AUTOFAC does not know which type instance should be returned. code example:

// class C1:i // class C2:i
Interface I {} class c1:i {} class C2:I {}

According to the above code, the last actual type associated with the I interface is C2,AUTOFAC in the order of registration, followed by the registration will overwrite the previously registered. If you want to prevent this default behavior (the same interface/type has multiple type associations, and subsequent associations overwrite the previous association), you can call the Preserveexistingdefaults method in the As method call, so that if the interface/type has already been associated with the registration, This association is invalid:

// class C1:i // class C2:i

The above code is obtained by resolve<i> () to the time C1 type instance.

an interface is associated with more than one type note

One of the interfaces mentioned here cannot be associated with more than one type, and is for this common registration and association. In fact, it can be named<>, meta<> this way to multi-link, on such topics, follow-up blog will be discussed.

The association type and the registration type are required to inherit/implement the relationship or for itself
Builder. Registertype<x> (). As<y> ();

When registering this association, X inherits or implements Y, or y is the X type, or throws an exception when builder calls the build method.

The End statement

By the end of this blog post, the most basic/common functions of AUTOFAC are finished. But now is only the most basic function, the recommendation is not the end, there are some content, I think still need to grasp, I hope you continue to pay attention to, thank you!

Autofac Comprehensive Parsing series (version: 3.5) –[use (recommended): 4. Type association (service exposure)]

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.