dotnet core通过配置文件进行注入

配置文件示例

{
  //描述:"实现类命名空间+实现类名称,所在程序集名称"
  "Services": {
    "Singleton": [

    ],
    "Transient": [
      {
        "Service": "Cy.NetCore.Common.Interfaces.IService,Cy.NetCore.Common.Interfaces",
        "Implementation": "Cy.NetCore.Common.DataBase.ServiceImpl.ServiceA,Cy.NetCore.Common.DataBase"
      }
    ],
    "AddScoped": [

    ]
  }
}

配置文件反序列化类

public class ServicesConfiguration
{
    public IEnumerable<ServiceItem> Singleton { get; set; }
    public IEnumerable<ServiceItem> Transient { get; set; }
    public IEnumerable<ServiceItem> AddScoped { get; set; }
}
public class ServiceItem
{
    public string Service { get; set; }
    public string Implementation { get; set; }
}

注入实现的扩展方法

public static class AddFromConfigurationFileExtension
{
    /// <summary>
    /// 通过配置文件进行注入实现。
    /// </summary>
    /// <remarks>
    /// 需要注意的是由于通过的配置文件进行配置,那么要确保接口、实现对应的程序集和
    /// typeof(AddFromConfigurationFileExtension).Assembly程序集同目录。
    /// 不然Type.GetType会找不到对应的类。
    /// </remarks>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    /// <returns></returns>
    public static IServiceCollection AddFromConfigurationFile(this IServiceCollection services,
    IConfigurationSection configuration)
    {
        var servicesConfiguration = configuration.Get<ServicesConfiguration>();            
        Type @interface = null, implementation = null;
        if (servicesConfiguration.Singleton != null)
        {
            foreach (var service in servicesConfiguration.Singleton)
            {
                @interface = Type.GetType(service.Service, false);
                implementation = Type.GetType(service.Implementation, false);
                if (@interface == null)
                    throw new ArgumentNullException($"{service.Service}未找到。请和管理员联系!", nameof(@interface));
                if (@interface == null)
                    throw new ArgumentNullException($"{service.Implementation}未找到。请和管理员联系!", nameof(implementation));
                services.AddSingleton(@interface,implementation);
            }
        }
        if (servicesConfiguration.Transient != null)
        {
            foreach (var service in servicesConfiguration.Transient)
            {
                //确保能够正确注册。防止影响后面的功能。
                @interface = Type.GetType(service.Service, false);
                implementation = Type.GetType(service.Implementation, false);
                if (@interface == null)
                    throw new ArgumentNullException($"{service.Service}未找到。请和管理员联系!", nameof(@interface));
                if (@interface == null)
                    throw new ArgumentNullException($"{service.Implementation}未找到。请和管理员联系!", nameof(implementation));
                services.AddTransient(@interface, implementation);
            }
        }
        if (servicesConfiguration.AddScoped!=null)
        {
            foreach (var service in servicesConfiguration.AddScoped)
            {
                //确保能够正确注册。防止影响后面的功能。
                @interface = Type.GetType(service.Service, false);
                implementation = Type.GetType(service.Implementation, false);
                if (@interface == null)
                    throw new ArgumentNullException($"{service.Service}未找到。请和管理员联系!", nameof(@interface));
                if (@interface == null)
                    throw new ArgumentNullException($"{service.Implementation}未找到。请和管理员联系!", nameof(implementation));
                services.AddScoped(@interface, implementation);
            }
        }
        return services;
    }
}

使用NUnit进行单元测试

[TestFixture]
internal class Tests
{
    private ServiceProvider serviceProvider;
    private IService _service;

    [SetUp]
    public void Setup()
    {
        var build = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("configuration.json", optional: true, reloadOnChange: true);
        var config = build.Build();
        ServiceCollection services = new ServiceCollection();
        services.AddFromConfigurationFile(config.GetSection("Services"));
        serviceProvider=services.BuildServiceProvider();
        _service = serviceProvider.GetRequiredService<IService>();
    }

    [Test]
    public void TestService()
    {
        int a = 10, b = 10;
        var result = _service.Calculation(a, b);
        Assert.NotNull(result);
        Assert.AreEqual(result, 20);            
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值