Alec Bryte
Alec Bryte

Reputation: 612

Configure ServiceCollection via JSON file

Is there an example of configuring dependency injection in .NET Core 2.0 via a JSON file that would contain interface -> class mappings? E.g.

var someServiceConfigBuilder = new ConfigurationBuilder();
someServiceConfigBuilder.AddJsonFile("someservice.json");
var someServiceConfig = someServiceConfigBuilder.Build();

var services = new ServiceCollection();
services.AddOptions();
services.Configure<SomeServiceOptions>(someServiceConfig);
services
    // TODO this should really come from the JSON config file
    .AddTransient<ISomeService, SomeService>();

So rather than hard-coding the mappings with calls to AddTransient(), it'd be great to have this info coming from the JSON file.

Is this supported? If yes, what's the expected format of the JSON config?

Upvotes: 4

Views: 1801

Answers (2)

shebin c babu
shebin c babu

Reputation: 1157

 public static void Injection(IServiceCollection services)

 {

  var jsonServices = JObject.Parse(File.ReadAllText("dependency.json"))["services"];

  var requiredServices = JsonConvert.DeserializeObject < List < Service >> (jsonServices.ToString());

  foreach(var service in requiredServices)

  {

   var serviceType = Type.GetType(service.ServiceType.Trim() + ", " + service.Assembly.Trim());

   var implementationType = Type.GetType(service.ImplementationType.Trim() + ", " + service.Assembly.Trim());

   var serviceLifetime = (ServiceLifetime) Enum.Parse(typeof(ServiceLifetime), service.Lifetime.Trim());

   var serviceDescriptor = new ServiceDescriptor(serviceType: serviceType,

    implementationType: implementationType,

    lifetime: serviceLifetime);

   services.Add(serviceDescriptor);

  }

For more details please click here

Upvotes: 0

Nkosi
Nkosi

Reputation: 247213

Replacing the default services container

The built-in services container is meant to serve the basic needs of the framework and most consumer applications built on it. However, developers can replace the built-in container with their preferred container. The ConfigureServices method typically returns void, but if its signature is changed to return IServiceProvider, a different container can be configured and returned. There are many IOC containers available for .NET.

(Emphasis mine)

Reference: Introduction to Dependency Injection in ASP.NET Core

With that I would suggest checking to see if there are already 3rd party DI frameworks that provide the feature and has an extension that can integrate with .Net Core.

Note

When using a third-party DI container, you must change ConfigureServices so that it returns IServiceProvider instead of void.

Upvotes: 4

Related Questions