asp.netdependency-injection.net-6.0unity-containerasp.net-core-6.0

How can the ASP.NET built-in DI read dependencies from a file at runtime?


As you can see in C# Unity container, we can configure a container (a list of dependency and object creation policy) from a file, and it is very good when, I want change a dependency (backend for interface) in the runtime environment without need to upload my project again, or in a dockerise paradigm, I do not need to build the Docker image again.

At now, I want to migrate to the ASP.NET 6 built-in DI, How can I provide the same functionality in the built-in DI?

For example, something like

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IProductService" type="UnityExample.Service.IProductService, UnityExample.Service" />
    <containers>
      <container name="Service">
        <register type="IProductService" mapTo="ProductService"/>
      </container>
    </containers>
  </unity>
</configuration>

Solution

  • While you could have a hard time making the new service provider compatible with Unity, consider switching to Autofac. Autofac can replace the builtin .NET Core's container and also it supports loading configuration from a file.