Provide support for configuring ServiceCollection in ASP.NET WebAPI or via IConfiguration
Install the package via nuget:
dotnet add package DependencyInjection.Configuration
Configuration is read using the extension FromConfiguration()
:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.FromConfiguration(builder.Configuration);
For console or WPF applications configuration can still be read using the extension FromConfiguration()
:
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "appsettings.json", optional: false, reloadOnChange: true)
.Build();
IServiceCollection services = new ServiceCollection();
services.FromConfiguration(configuration);
Services definition is read from appsettings.json
:
{
"Services": {
"Collection": [
{
"ServiceType": "Samples.Lib.Interfaces.IRepository, Samples.Lib",
"ImplementationType": "Samples.Lib.Impl.Repository, Samples.Lib",
"Lifetime": "Scoped"
},
{
"ServiceType": "Samples.Lib.Interfaces.IService, Samples.Lib",
"ImplementationType": "Samples.Lib.Impl.Service, Samples.Lib"
},
{
"ServiceType": "Samples.Lib.Impl.Context, Samples.Lib",
"Lifetime": "Singleton"
},
{
"ServiceType": "Samples.Lib.Interfaces.IGenericService`1, Samples.Lib",
"ImplementationType": "Samples.Lib.Impl.GenericService`1, Samples.Lib"
},
{
"ServiceType": "Samples.Lib.Interfaces.IComplexService, Samples.Lib",
"Factory": {
"Type": "Samples.Lib.Factories.ComplexServiceFactory, Samples.Lib",
"Method": "Create"
},
"Lifetime": "Transient"
}
]
}
}
Per registration the following parameters can be set
ServiceType
: Assembly Qualified Name of the type to register (Required)ImplementationType
: Assembly Qualified Name of the type that implementsServiceType
(Optional)Lifetime
: lifetime of the registration (Optional). Values are taken from enum ServiceLifetime. If not provided it defaults toServiceLifetime.Transient
Factory
: create the service via factory method.Type
: Type where the factory method is definedMethod
: Factory method (has to be defined as static)
The JSON location of services definition can be changed in options:
var options = new DependencyInjectionConfigurationOptions
{
Path = "SomeOtherPath"
};
services.FromConfiguration(configuration, options);
For console or WebApi examples check out the samples directory.