.NET怎样配置JSON中依赖注入

发布时间:2021-01-29 15:56:50 作者:小新
来源:亿速云 阅读:143

这篇文章主要介绍了.NET怎样配置JSON中依赖注入,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

前言

在以前的 ASP.NET 4+ (MVC,Web Api,Owin,SingalR等)时候,都是提供了专有的接口以供使用第三方的依赖注入组件,比如我们常用的会使用 Autofac、Untiy、String.Net 等,这些第三放依赖注入组件基本上都提供了一套配置注入或者配置生命周期的方式,除了直接配置到类里面之外,还提供了要么使用 xml 文件,要么使用 json 等,那么在新的 ASP.NET Core 中微软已经默认的给我们提供了一个依赖注入的功能,我们就不再需要借助于第三方组件来实现依赖注入了,但是有时候我们想在配置文件中来配置依赖注入,微软本身的 DI 组件并没有给我们提供一个可供配置的文件,那么我们就需要自己来实现这个配置项的功能。个人觉得其主要使用场景是一些在编译时不能确定实现的,需要动态修改实现的地方。

下面就来看看应该如何来做这件事情吧。

Getting Started

首先,在应用程序中我们创建一个接口,以供 DI使用:

public interface IFoo
{
  string GetInputString(string input);
}

然后,添加一个 IFoo 接口的实现 Foo

public class Foo : IFoo
{
  public string GetInputString(string input)
  {
    return $"输入的字符串为:{ input }";
  }
}

接下来,我们需要把以上的 IFoo 接口和它的实现添加到 Startup.cs 文件中的ConfigureServices方法中,ConfigureServices 主要是用来配置依赖注入服务的。然后通过该方法提供的ISerciceCollection接口参数注入 Services。

public void ConfigureServices(IServiceCollection services)
{
  services.Add(new ServiceDescriptor(serviceType: typeof(IFoo), 
                    implementationType: typeof(Foo), 
                    lifetime: ServiceLifetime.Transient));
}

这里,我们使用到了 IServiceCollection 里面的 Add 方法,添加一个生命周期为瞬态的 IFoo 的实现。瞬态就是说在每次请求的时候都将创建一个Foo的实例。

以上是默认微软为我们提供的添加依赖注入的方法,下面我们来看一下怎么来改造成我们需要的使用 json 文件的方式。

使用 json 文件配置 DI

当我们使用json文件配置依赖注入的时候,可以选择新建一个json文件,也可以直接使用 appsettings.json 文件。现在我们就直接在 appsettings.json 文件中添加关于DI的配置了。

appsettings.json

 "Logging": {
  "IncludeScopes": false,
  "LogLevel": {
   "Default": "Debug",
   "System": "Information",
   "Microsoft": "Information"
  }
 },

 "DIServices": [
  {
   "serviceType": "[namesapce].IFoo",
   "implementationType": "[namesapce].Foo",
   "lifetime": "Transient"
  }
 ]
}

首先,添加一个名为 “DIServices” 的数组节点,数组中包含一个或多个配置service的对象,serviceType代表服务接口的类型,implementationType接口的实现,lifetime 初始化实例的生命周期。

注意:配置文件中的类型必须为全名称,即包含命名空间。

接下来,添加一个和Json文件配置项相对应的一个service类,这里我们需要使用 Newtonsoft 这个json库。

using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public class Service
{
  public string ServiceType { get; set; }

  public string ImplementationType { get;set; }

  [JsonConverter(typeof(StringEnumConverter))]
  public ServiceLifetime Lifetime { get; set; }
}

然后需要改造一下ConfigureServices,在 ConfigureServices 中读取配置的 json文件即可。

public void ConfigureServices(IServiceCollection services)
{
  //services.Add(new ServiceDescriptor(serviceType: typeof(IFoo),
  //            implementationType: typeof(Foo),
  //            lifetime: ServiceLifetime.Transient));

  var jsonServices = JObject.Parse(File.ReadAllText("appSettings.json"))["DIServices"];
  var requiredServices = JsonConvert.DeserializeObject<List<Service>>(jsonServices.ToString());

  foreach (var service in requiredServices) {
    services.Add(new ServiceDescriptor(serviceType: Type.GetType(service.ServiceType),
                      implementationType: Type.GetType(service.ImplementationType),
                      lifetime: service.Lifetime));
  }
}

然后我们测试一下是否是可用的。

测试

打开 HomeController.cs ,添加注入项:

public class HomeController : Controller
{
  private readonly IFoo _foo;

  public HomeController(IFoo foo) 
  {
    _foo = foo;
  }

  public IActionResult About() 
  {
    ViewData["Message"] = _foo.GetInputString("Your application description page.");

    return View();
  }
}

在 HomeController的构造函数添加IFoo接口,然后在 About 的Action中使用。

运行程序,打开页面,点击 About标签

.NET怎样配置JSON中依赖注入

感谢你能够认真阅读完这篇文章,希望小编分享的“.NET怎样配置JSON中依赖注入”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

推荐阅读:
  1. .Net Core如何读取Json配置文件中的参数
  2. 介绍asp.net core 依赖注入

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

json

上一篇:使用android控件怎么实现一个单击拖动效果

下一篇:怎么在Postgresql 数据库中转义字符

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》