AUTOFAC Official document (18) "Json/xml Configuration"

Source: Internet
Author: User
Tags mscorlib reflection

Most IOC containers provide programming interfaces and configuration support based on Json/xml files, AUTOFAC is no exception.

AUTOFAC encourages programmatic configuration through the Containerbuilder class. The use of programming interfaces is the core of container design. If you cannot select or configure specific classes at compile time, it is recommended that you use JSON or XML.

Before delving into the Json/xml configuration, be sure to read the module-which explains how to handle more complex scenarios than the basic Json/xml component registration allows. The configuration in Json/xml is not a functional feature replacement for programmatic configuration, so complex scenarios may require a combination of json/xml and modules.

    Configuring with Microsoft Configuration (4.0+)
        Quick Start
        Default Assembly
        components
        Modules Type Names
        differences from Legacy Configuration
        Additional Tips
    Configuring with Application Configuration (Legacy Pre-4.0)
        Setup
        components
        Modules
        Config Files
        Configuring the Container
        multiple Files or Sections

Quick Start configuration using Microsoft Configuration (4.0+)

Attention

Microsoft configuration applies to the 4.0+ version of Autofac.configuration. It does not apply to previous versions of the configuration pack.

With the release of Microsoft.Extensions.Configuration and Autofac.configuration 4.0.0, AUTOFAC will be limited to application configuration files by leveraging a more flexible configuration model that was not previously available. If you have previously used a app.config or Web.config configuration, you will need to migrate the configuration to the new format and update how the configuration is set up with the application container. Quick Start

The basic steps for obtaining a configuration using your application are:

Set your configuration in a JSON or XML file that can be read by Microsoft.Extensions.Configuration.

Json Configuration using Microsoft.Extensions.Configuration.Json

XML Configuration using MICROSOFT.EXTENSIONS.CONFIGURATION.XML

Build configurations using Microsoft.Extensions.Configuration.ConfigurationBuilder.

Create a new Autofac.Configuration.ConfigurationModule and pass the build Microsoft.Extensions.Configuration.IConfiguration to it.

Register the Autofac.Configuration.ConfigurationModule with your container.

Some of the simple registered configuration files are as follows:

{
  ' defaultassembly ': ' Autofac.Example.Calculator ', '
  components ': [{
    ' type ': ' AUTOFAC.EXAMPLE.CALCULATOR.ADDITION.ADD, Autofac.Example.Calculator.Addition ",
    Services": [{
      ' type ': '] Autofac.Example.Calculator.Api.IOperation '
    }],
    ' injectproperties ': true
  }, {
    ' type ': ' Autofac.Example.Calculator.Division.Divide, Autofac.Example.Calculator.Division ",
    Services": [{
      ' type ' : "Autofac.Example.Calculator.Api.IOperation"
    }],
    "parameters": {
      "Places": 4
    }
  }]
}

JSON is clearer and easier to read, but if you prefer XML, the same configuration looks like this:

<?xml version= "1.0" encoding= "Utf-8"?> <autofac defaultassembly=
"Autofac.Example.Calculator" >
    <components name= "0" >
        <type>autofac.example.calculator.addition.add, autofac.example.calculator.addition</type>
        <services name= "0" type= " Autofac.Example.Calculator.Api.IOperation "/>
        <injectProperties>true</injectProperties>
    </components>
    <components name= "1" >
        <type>autofac.example.calculator.division.divide, autofac.example.calculator.division</type>
        <services name= "0" type= " Autofac.Example.Calculator.Api.IOperation "/>
        <injectProperties>true</injectProperties>
        <parameters>
            <places>4</places>
        </parameters>
    </components>
</autofac>

Note the sequence "naming" of components and services in XML-this is the way Microsoft.Extensions.Configuration processes sequence collections (arrays).

Build your configuration and register with AUTOFAC Containerbuilder as follows:

Add configuration to Configurationbuilder
var config = new Configurationbuilder ();
Config. Addjsonfile from Microsoft.Extensions.Configuration.Json
//config. Addxmlfile from Microsoft.Extensions.Configuration.Xml
config. Addjsonfile ("Autofac.json");

Register Configurationmodule
var module = new Configurationmodule (config) with AUTOFAC. Build ());
var builder = new Containerbuilder ();
Builder. Registermodule (module);
Default Assembly

You can specify a default assembly option in the configuration to help write the type in a shorter way. If you do not specify an assembly-qualified type name in a type or interface reference, the default assembly is assumed.

{
  "defaultassembly": "Autofac.Example.Calculator"
}
Component

Components are the most common things that you will register. You can specify parameters from the lifecycle scope on each component.

Component is added to the top-level components element in the configuration. Inside is an array of the components you want to register.

This example shows a component that contains all the options for the purpose of the syntax specification only. You do not actually use each of these in the registration of each component.

{
  ' components ': [{
    ' type ': ' Autofac.Example.Calculator.Addition.Add, Autofac.Example.Calculator.Addition ' ,
    ' services ': [{
      ' type ': ' Autofac.Example.Calculator.Api.IOperation '
    }, {
      ' type ': ' Autofac.Example.Calculator.Api.IAddOperation ",
      " key ":" Add "
    },
    " AutoActivate ": True,
    " Injectproperties ": True,
    " Instancescope ":" Per-dependency ",
    " metadata ": [{
      key]:" Answer ",
      " Value ":", "
      type": "System.Int32, mscorlib"
    }],
    "ownership": "external",
    "parameters": {
      "Places": 4
    },
    "Properties": {
      "Dictionaryprop": {
        "key": "Value"
      },
      "Listprop": [1, 2 , 3, 4, 5]}}}
Element Name Description Valid Values
Type The only required thing. The concrete class of the component (assembly-qualified if in a assembly other than the default). Any. NET type name, can created through reflection.
Services An array of services exposed by the component. Each service must have a type and may optionally specify a key. Any. NET type name, can created through reflection.
AutoActivate A Boolean indicating if the component should auto-activate. True, False
Injectproperties A Boolean indicating whether property (setter) injection for the component should is enabled. True, False
Instancescope Instance scope for the component. SingleInstance, Perlifetimescope, Perdependency, perrequest
Metadata An array of metadata values to associate with the component. Each item specifies the name, type, and value. Any metadata values.
Ownership Allows for control whether the lifetime scope disposes the component or your code does. Lifetimescope, External
Parameters A name/value dictionary where the name of each element is the name of a constructor parameter and the value is the value t o inject. Any parameter in the constructor of the component type.
Properties A name/value dictionary where the name of each element is the name of a and the ' value ' to inject. Any settable the component type.

Note that both parameters and properties support both dictionary and enumerable values. You can see how to specify these examples in the JSON structure above. Module

When using modules with AUTOFAC, you can register these modules with components when you use the configuration.

Module is added to the top-level modules element in the configuration. Inside is an array of the modules you want to register.

This example shows a module that contains all the options for syntax purposes only. You will not use each of the module registrations.

{
  ' modules ': [{
    ' type ': ' Autofac.Example.Calculator.OperationModule, Autofac.Example.Calculator ',
    ' Parameters ": {
      " Places ": 4
    },
    " Properties ": {
      " Dictionaryprop ": {"
        key ":" Value "
      },
      " Listprop ": [1, 2, 3, 4, 5]}}
  ]
}
element Name description

Note that both parameters and properties support dictionaries and enumerable values. You can see how to specify these examples in the JSON structure above.

If you prefer, you can register the same module multiple times with different parameter/attribute sets. type name

In all cases where you see the type name (component type, service type, module type), you want to be a standard assembly-qualified type name that you can usually pass to Type.GetType (String typename). If the type is in defaultassembly, the assembly name can be closed, but it will not be harmed in any way.

An assembly-qualified type name has a complete type that contains a namespace, a comma, and an assembly name, such as Autofac.example.calculator.operationmodule,autofac.example.calculator. In this case, the Autofac.Example.Calculator.OperationModule is the type, which is in the Autofac.Example.Calculator assembly.

Generics are a bit more complex. The configuration does not support open generics, so you must also specify the fully qualified name of each generic parameter.

For example, suppose you have a repository irepository<t> in a configwithgenericsdemo assembly. We also want to say that you have a stringrepository class that implements the Irepository<string>. To register in the configuration, it looks like this:

{
  ' components ': [{
    ' type ': ' Configwithgenericsdemo.stringrepository, Configwithgenericsdemo ',
    ' Services ': [{
      ' type ': ' Configwithgenericsdemo.irepository ' 1[[system.string, mscorlib]], Configwithgenericsdemo "
    }]
  }]
}

If you find it difficult to figure out what your type name is, you can do so in your code:

Writes the type name to the debug Output window and copies/pastes it into your configuration.
System.Diagnostics.Debug.WriteLine (typeof (Irepository<string>). AssemblyQualifiedName);
differences from traditional configurations

When migrating to a new format from an app.config based format based on an older version (version 4.0), you need to be aware of some of the following important changes:

No configurationsettingsreader. Microsoft.Extensions.Configuration completely replaces the old XML format configuration. Legacy configuration documents are not available for 4.0+ series configuration packages.

Multiple profiles are handled differently. The old configuration has a file element that can automatically pull multiple files together for configuration. Now use Microsoft.Extensions.Configuration.ConfigurationBuilder to complete this operation. Support AutoActivate. You can specify that the component is now automatically activated, which is previously unavailable in the configuration. XML uses element child elements rather than attributes. This helps to keep XML and JSON parsing the same when using Microsoft.Extensions.Configuration so that you can combine the XML and JSON configuration sources correctly. Using XML requires that you use digital naming components and services. Microsoft.Extensions.Configuration requires that each configuration item have a name and a value. It supports sequential collections (arrays) by implicitly naming elements with numbers ("0", "1", and so on) in the collection name. You can see this example in the Quick start above. If you do not use JSON, you need to view this requirement from Microsoft.Extensions.Configuration, or you will not get what you expect. The lifetime scope of each request is supported. Previously, you could not configure an element to have a lifetime range of each request. Now you can. The dotted line in the name/value disappears. The name of the XML element is used to contain dashes such as injection attributes-
Use JSON to configure the format, which is now a hump-like injectproperties. The service is specified in a child element. Legacy configurations allow services to be properly declared at the top of the component. The new system requires that all services be included in the service collection. More Tips

The new Microsoft.Extensions.Configuration mechanism adds a lot of flexibility. You might want to take advantage of something: environment variable support. You can use Microsoft.Extensions.Configuration.EnvironmentVariables to enable environment-based configuration changes. A quick way to debug or fix something without touching the code may be to switch AUTOFAC registration based on the environment. A simple configuration merge.
Configurationbuilder allows you to create configurations from a number of sources and merge them into one. If you have many configurations, consider scanning your profile and dynamically building the configuration, rather than hard-coded paths. Customize the configuration source. You can implement Microsoft.Extensions.Configuration.ConfigurationProvider yourself to support more than just files. If you want to centrally configure, consider the configuration sources supported by the database or REST API. Configuring using Application Configuration (Legacy 4.0 previous versions)

Attention

The traditional application configuration described below applies to the 3.x and earlier versions of Autofac.configuration. It does not apply to the 4.0 + version of the package.

Before publishing the Microsoft.Extensions.Configuration and updated configuration model, AUTOFAC is bound to the standard. NET application configuration file. (App.config/web.config). In the 3.x series of the Autofac.configuration package, this is the way to configure things. Establish

Using the traditional configuration mechanism, you need to declare a section handler somewhere near the top of your profile:

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
    <configSections>
        < Section name= "AUTOFAC" type= "Autofac.Configuration.SectionHandler, autofac.configuration"/> </
    Configsections>

Then, provide a section that describes your component:

<AUTOFAC defaultassembly= "Autofac.Example.Calculator.Api" >
    <components>
        <component
            Type= "Autofac.Example.Calculator.Addition.Add, Autofac.Example.Calculator.Addition"
            service= " Autofac.Example.Calculator.Api.IOperation "/>

        <component
            type=" Autofac.Example.Calculator.Division.Divide, Autofac.Example.Calculator.Division "
            service=" Autofac.Example.Calculator.Api.IOperation ">
            <parameters>
                <parameter name=" Places "value=" 4 "/>
            </parameters>
        </component>

Components
The Defaultassembly property is optional and allows namespace-qualified rather than fully qualified type names to be used. This can save some confusion and typing, especially if you use a profile for each assembly (see the other configuration files below). Component

Components are the most common things that you will register. You can specify parameters from the lifecycle scope on each component. Component Properties

The following properties can be used as component elements (the default value is the same as the programming API):

Attribute Name Description Valid Values
Type The only required attribute. The concrete class of the component (assembly-qualified if in a assembly other than the default.) Any. NET type name, can created through reflection.
Service A service exposed by the component. For more than one service, use the nested services element. As for type.
Instance-scope Instance Scope-see Instance scope. Per-dependency, single-instance or Per-lifetime-scope
Instance-ownership Container ' s ownership over the Instances-see the Instanceownership enumeration. Lifetime-scope or external
Name A string name for the component. Any non-empty string value.
Inject-properties The Enable property (setter) is injection for the component. Yes, No.
Component child elements
Element Description
Services A List of service elements, whose element content contains the names of types exposed as services by the component (= th E service attribute.)
Parameters A List of explicit constructor parameters to set on the instances (for the example.)
Properties A List of explicit property values to set (syntax as for parameters.)
Metadata A List of item nodes with name, value and type attributes.

The XML configuration syntax lacks some features that can be obtained through the programming API, such as registering generics. It is recommended that you use modules in these cases. Module

The Component Configuration container is very detailed and can quickly get detailed results. AUTOFAC supports packaging components into modules to encapsulate implementations while providing flexible configuration.

Modules are registered by type:

<modules>
    <module type= "MyModule"/>

You can add nested parameters and properties to the module registration in the same way as the above components. Other configuration Files

You can use the following additional configuration files:

<files>
    <file name= "Controllers.config" section= "Controllers"/>
Configuration Container

First, you must refer to Autofac.Configuration.dll from your project.

To configure the container, use Configurationsettingsreader and use the name you gave to the XML configuration section to initialize:

var builder = new Containerbuilder ();
Builder. Registermodule (New Configurationsettingsreader ("mycomponents"));
Register other components and call build () to create the container.

The container settings reader overrides the default component that has already been registered; You can write your application to run with a reasonable default value, and then overwrite only the component registrations that are required for a specific deployment. multiple files or parts

If you provide a file name to the Configurationsettingsreader constructor, you can use multiple settings readers in the same container to read different segments or even different profiles.

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.