What is key
in configuration file?
I found the special term in autofac configuration file, but I do not know, what is the meaning of that? and when I have to use that?
{
"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"
}]
}
As you can see in autofac documentation, autofac has a concept who is called Keyed Services
, this concept describe like below
Autofac provides three typical ways to identify services. However, you can also identify services by a string name or by an object key. Using strings as component names is convenient in some cases, but in others we may wish to use keys of other types. Keyed services provide this ability.
For example, an string describe the different device states in our example:
Each string value corresponds to an implementation of the service:
public class OnlineState : IDeviceState { }
The string values can then be registered as keys for the implementations as shown below.
var builder = new ContainerBuilder();
builder.RegisterType<OnlineState>().Keyed<IDeviceState>("Online");
builder.RegisterType<OfflineState>().Keyed<IDeviceState>("Offline");
// Register other components here
the requivalent of Keyed
method in configuration file is key
term, when used in service registration.