Configuration support for Autofac IoC
Configuration support for Autofac.
Please file issues and pull requests for this package in this repository rather than in the Autofac core repo.
The basic steps to getting configuration set up with your application are:
Microsoft.Extensions.Configuration
.
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.Configuration.Xml
Microsoft.Extensions.Configuration.ConfigurationBuilder
.Autofac.Configuration.ConfigurationModule
and pass the built Microsoft.Extensions.Configuration.IConfiguration
into it.Autofac.Configuration.ConfigurationModule
with your container.A configuration file with some simple registrations looks like this:
{
"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 cleaner 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 ordinal "naming" of components and services in XML - this is due to the way Microsoft.Extensions.Configuration handles ordinal collections (arrays).
Build up your configuration and register it with the Autofac ContainerBuilder
like this:
// Add the configuration to the ConfigurationBuilder.
var config = new ConfigurationBuilder();
// config.AddJsonFile comes from Microsoft.Extensions.Configuration.Json
// config.AddXmlFile comes from Microsoft.Extensions.Configuration.Xml
config.AddJsonFile("autofac.json");
// Register the ConfigurationModule with Autofac.
var module = new ConfigurationModule(config.Build());
var builder = new ContainerBuilder();
builder.RegisterModule(module);
Check out the Autofac configuration documentation for more information.
Need help with Autofac? We have a documentation site as well as API documentation. We're ready to answer your questions on Stack Overflow or check out the discussion forum.