How does autofac register components (registering components)

Source: Internet
Author: User

In the previous step of using autofac, we know that autofac createsThe containerbuilder object is used to register components. This builder exposes components through services. In the future, we only need to know the service to obtain the specific component instance.

In terms of autofac, click here to view => terms

What is component )?

There are three types:

1. Reflection (. NET type, or generic)

2. Ready-made instances (instances of the type we created)

3. Lambda expressions (execute anonymous functions of Object Instantiation)

Auotfac isContainerbuilder providesRegister ()Set the family method to register the component. Each component is calledContainerbuilderOfAs ()Method To expose one or more services.

// Create a builder. var builder = new containerbuilder () for registering components/services ();
// Register a type builder. registertype <consolelogger>. As <ilogger> (); // register a ready-made instance
VaR output = new stringwriter (); builder. registerinstance (output ). as <textwriter> (); // registers an expression for executing the object creation. builder. register (C => New configreader ("mysection ")). as <iconfigreader> ();
// Construct a iner to complete the registration action, and save the container for later parsing object. var Container = builder. Build ();
// Now we can parse the service and wait until we want to be an instance. Using (VAR scope = container. beginlifetimescope () {var reader = container. Resolve <iconfigreader> ();}
  1. I. Reflection component

There are two reflection registration methods, one is a generic method, and the other is a common method (the input parameter type is type ).

Below are the two registration methods.

var builder = new ContainerBuilder();builder.RegisterType<ConsoleLogger>();builder.RegisterType(typeof(ConfigReader));

When the reflection-based component is used, autofac automatically uses the constructor with the most class parameters. This parameter must be parsed from the container.
For example:

I have such a class.

public class MyClass{    public MyClass() { /* ... */ }    public MyClass(ILogger logger) { /* ... */ }    public MyClass(ILogger logger, IConfigReader reader) { /* ... */ }}

Then I register the component in aufo:

var builder = new ContainerBuilder();builder.RegisterType<MyClass>();builder.RegisterType<ConsoleLogger>().As<ILogger>();var container = builder.Build();using(var scope = container.BeginLifetimeScope()){  var component = container.Resolve<MyComponent>();}

At this time, we can find that the constructor with the most parameters is the 2nd constructor of the myclass class, but not the 3rd constructor. because we have registered the components of the ilogger service, but have not registered the components of the iconfigreader service. therefore, the container can parse a parameter of the constructor. Therefore, aufofac automatically selects 2nd constructor.
I can also change the behavior of the automatically selected constructor of aufofac to achieve manual selection.The usingconstructor method can meet our requirements.

builder.RegisterType<MyClass>()       .UsingConstructor(typeof(ILogger), typeof(IConfigReader));

Summary based on reflection components:

1. Any component type must pass"Registertype"Method registration, and the registration type must be a specific type, not an interface or abstract type. although we can expose an interface or abstract class as a service, we cannot register them as components.

2. I can useUsingconstructorMethod To change the features of the autofac automatically selected constructor.

Ii. instance components.

We can use"Registerinstance"Method: register the instance of the created object to the service. expose it to you through the service.

var output = new StringWriter();builder.RegisterInstance(output).As<TextWriter>();

Iii. Lambda expression Components
The reflection component is a good choice, but sometimes the creation logic of the component is not a simple constructor call, but a complicated logic, therefore, autofac allows a delegate or Lambda expression to be used as the creator of a component.

builder.Register(c => new A(c.Resolve<B>()));

Note: In the code above, we can see that there isCThe parameter is provided to the expression. This parameter is the component context (Icomponentcontext type object), we can use it in the expression to parse the instance you need to create the component from the container.

 

 

 

How does autofac register components (registering components)

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.