/dependency-injection-configuration

Provide JSON configuration for ServiceCollection

Primary LanguageC#Apache License 2.0Apache-2.0

Dependency Injection Configuration Build status NuGet

Provide support for configuring ServiceCollection in ASP.NET WebAPI or via IConfiguration

Installation

Install the package via nuget:

dotnet add package DependencyInjection.Configuration

Web Api

Configuration is read using the extension FromConfiguration():

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.FromConfiguration(builder.Configuration);

IConfiguration

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);

Definition

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 implements ServiceType (Optional)
  • Lifetime: lifetime of the registration (Optional). Values are taken from enum ServiceLifetime. If not provided it defaults to ServiceLifetime.Transient
  • Factory: create the service via factory method.
    • Type: Type where the factory method is defined
    • Method: 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.