当前位置: 移动技术网 > IT编程>开发语言>.net > 详解ASP.NET Core 在 JSON 文件中配置依赖注入

详解ASP.NET Core 在 JSON 文件中配置依赖注入

2017年12月08日  | 移动技术网IT编程  | 我要评论

小狗拉肚子吃什么药,圣城家园老友记,蛊域

前言

在上一篇文章中写了如何在mvc中配置全局路由前缀,今天给大家介绍一下如何在在 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标签

总结

以上即为在 asp.net core 中配置依赖注入到json文件中,这只是一个简单的实例,不要用在生产环境中。在实际的项目中你还需要处理关于读取配置异常情况,服务是否存在的异常情况,生命周期等等这些问题。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网