简单使用 Mvc 内置的 Ioc

  本文基于 .NET Core 2.0。

  鉴于网上的文章理论较多,鄙人不才,想整理一份 Hello World(Demo)版的文章。

目录

  • 场景一:简单类的使用
  • 场景二:包含接口类的使用
  • 场景三:涉及引用类库的使用

场景一:简单类的使用

  类 DemoService.cs:

    public class DemoService
    {
        public string Test()
        {
            return Guid.NewGuid().ToString();
        }
    }

  控制器 DemoController.cs:

    public class DemoController : Controller
    {
        private readonly DemoService _demoService;

        public DemoController(DemoService demoService)
        {
            _demoService = demoService;
        }

        public IActionResult Index()
        {
            return Json(_demoService.Test());
        }
    }

  需要先在 Startup.cs 下的 ConfigureServices() 方法中进行注册才能使用,这里提供了三种方法,可以选择自己喜欢的方式进行注册。

    //方法一
    services.AddSingleton(typeof(DemoService), new DemoService());

    //方法二
    services.AddSingleton(typeof(DemoService));

    //方法三
    services.AddSingleton<DemoService>();

  执行输出结果,正常:

  IOC 的容器目前有三种生命周期 Transient、Scoped 和 Singleton,使用方式大致相同,具体差异不在这里进行叙述:

    //范例
    services.AddTransient(typeof(DemoService));
    services.AddScoped<DemoService>();

场景二:包含接口类的使用

  接口 IDemo2Service.cs:

    public interface IDemo2Service
    {
        string Test();
    }

  接口实现 Demo2Service.cs:

    public class Demo2Service : IDemo2Service
    {
        public string Test()
        {
            return Guid.NewGuid().ToString();
        }
    }

  控制器 Demo2Controller.cs:

    public class Demo2Controller : Controller
    {
        private readonly IDemo2Service _demoService;

        public Demo2Controller(IDemo2Service demoService)
        {
            _demoService = demoService;
        }

        public IActionResult Index()
        {
            return Json(_demoService.Test());
        }
    }

  目前需要在类 Startup.cs 中的 ConfigureServices() 方法内新增的注册方法如下(可选其一):

    //方法一
    services.AddSingleton(typeof(IDemo2Service), new Demo2Service());

    //方法二
    services.AddSingleton(typeof(IDemo2Service), typeof(Demo2Service));

    //方法三
    services.AddSingleton<IDemo2Service, Demo2Service>();

  输出结果正常:

场景三:涉及引用类库的使用

  我们先新增一个用于标识作用的接口 IServiceSupport.cs,该接口没有包含方法,只是一个标识作用,有点类似 DDD 的聚合根接口 IAggregateRoot:

    public interface IServiceSupport
    {
    }

  接口 IDemo3Service.cs

    public interface IDemo3Service
    {
        string Test();
    }

  接口实现 Demo3Service.cs

    public class Demo3Service : IDemo3Service
    {
        public string Test()
        {
            return Guid.NewGuid().ToString();
        }
    }

  这次我们统一编写一个方法将该类库下的所有接口和实现进行注册:

        private static void AddSingletonServices(IServiceCollection services)
        {
            var asm = Assembly.Load(new AssemblyName("IocCoreDemo.Services"));
            var serviceTypes = asm.GetTypes()
                .Where(x => typeof(IServiceSupport).IsAssignableFrom(x) && !x.GetTypeInfo().IsAbstract);

            foreach (var serviceType in serviceTypes)
            {
                foreach (var serviceInterface in serviceType.GetInterfaces())
                {
                    services.AddSingleton(serviceInterface, serviceType);
                }
            }
        }

  因为使用了反射,所以需要 using System.Reflection;

  这次我们在 Startup.cs 类中添加和修改的方法如图所示:

   Startup.cs 类中使用的有效命名空间如下:

using IocCoreDemo.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection;

  

  如果注入失败,执行结果便会如图所示:

  为什么会出现上图的情况呢?因为小编忘记把接口 IDemo3Service 继承自接口 IServiceSupport 了,接下来我们只需要做出一个继承的编写操作即可:

  再次执行启动,结果便如你所料:

原文地址:http://www.cnblogs.com/liqingwen/p/8571366.html


相关的文章:

  《[.Net Core] 简单读取 json 配置文件

  《[.Net Core] 简单使用 Mvc 内置的 Ioc

  《[.Net Core] 简单使用 Mvc 内置的 Ioc(续)

  《[.Net Core] 在 Mvc 中简单使用日志组件

简单使用 Mvc 内置的 Ioc的更多相关文章

  1. [.Net Core] 简单使用 Mvc 内置的 Ioc

    简单使用 Mvc 内置的 Ioc 本文基于 .NET Core 2.0. 鉴于网上的文章理论较多,鄙人不才,想整理一份 Hello World(Demo)版的文章. 目录 场景一:简单类的使用 场景二 ...

  2. [.Net Core] 简单使用 Mvc 内置的 Ioc(续)

    简单使用 Mvc 内置的 Ioc(续) 本文基于 .NET Core 2.0. 上一章<[.Net Core] 简单使用 Mvc 内置的 Ioc>已经对日常 Mvc 中的 Ioc 的简单用 ...

  3. ASP.NET Core Web 应用程序系列(一)- 使用ASP.NET Core内置的IoC容器DI进行批量依赖注入(MVC当中应用)

    在正式进入主题之前我们来看下几个概念: 一.依赖倒置 依赖倒置是编程五大原则之一,即: 1.上层模块不应该依赖于下层模块,它们共同依赖于一个抽象. 2.抽象不能依赖于具体,具体依赖于抽象. 其中上层就 ...

  4. Spring MVC内置支持的4种内容协商方式【享学Spring MVC】

    每篇一句 十个光头九个富,最后一个会砍树 前言 不知你在使用Spring Boot时是否对这样一个现象"诧异"过:同一个接口(同一个URL)在接口报错情况下,若你用rest访问,它 ...

  5. ASP.NET CORE 内置的IOC解读及使用

    在我接触IOC和DI 概念的时候是在2016年有幸倒腾Java的时候第一次接触,当时对这两个概念很是模糊:后来由于各种原因又回到.net 大本营,又再次接触了IOC和DI,也算终于搞清楚了IOC和DI ...

  6. MVC路由 路由的三种扩展 替换MVC内置的Handler

    Global.asax 是 程序入口文件 路由配置   为什么localhost:8088/Home/Index/1 能返问到我们写的 会去掉前缀跟端口号  变成Home/Index/1 用这个跟路由 ...

  7. ASP.NET MVC内置的Filter实现介绍

    有时候你想在调用action方法之前或者action方法之后处理一些逻辑,为了支持这个,ASP.NET MVC允许你创建action过滤器.Action过滤器是自定义的Attributes,用来标记添 ...

  8. ASP.NET Core MVC内置服务的使用

    ASP.NET Core中的依赖注入可以说是无处不在,其通过创建一个ServiceCollection对象并将服务注册信息以ServiceDescriptor对象的形式添加在其中,其次针对Servic ...

  9. .net MVC内置js验证 jquery.validate.unobtrusive.js重置验证操作(备忘,找了很多次了)

    (function ($) { $.validator.unobtrusive.parseDynamicContent = function (selector) { //use the normal ...

随机推荐

  1. Struts 2 动作注释 配置动作扩展 全局开关

    动作注释package com.yiibai.user.action; import org.apache.struts2.convention.annotation.Action; import o ...

  2. ASP.NET MVC 通用角色权限管理系统

    RightControl 介绍 .NET 通用后台角色权限管理系统,已完成.项目地址:http://106.14.77.184/Admin/Login 码云地址:https://gitee.com/L ...

  3. VisionPro显示隐藏搜索区域

    假如我们需要显示两张图,一张显示CogPMAlignTool工具不带搜索区域的,一张显示CogPMAlignTool工具带搜索区域的图像 VisionPro显示隐藏搜索区域 VisionPro显示隐藏 ...

  4. shiro 系列

    http://jinnianshilongnian.iteye.com/blog/2019547 shiro学习以及附带DEMO地址: http://www.sojson.com/shiro ,git ...

  5. 3,bool值之间的转换,和str的各个功能属性。

    bool值之间的转换 and 空字符串即为False   字符串内有内容即为True. a = 11 c = str(a) #int转换成str print(type(c)) a = ' b = in ...

  6. linux 搭建apache 服务器

    1.查看apache服务器 /etc/init.d/httpd status 若没有,则使用yum  -y install httpd  安装软件 2.设置开机启动 chkconfig httpd o ...

  7. luogu1231 教辅的组成

    注意把书拆成两份 #include <iostream> #include <cstring> #include <cstdio> #include <que ...

  8. iOS学习笔记07-运动事件和远程控制

    之前我们已经学习了触摸处理和手势识别,其实这两个同属于iOS事件的触摸事件,今天我们来学习下iOS事件的另外两个事件: 一.运动事件 运动事件,是通过加速器进行触发,和触摸事件一样,继承UIRespo ...

  9. BZOJ1926 [Sdoi2010]粟粟的书架 【主席树 + 二分 + 前缀和】

    题目 幸福幼儿园 B29 班的粟粟是一个聪明机灵.乖巧可爱的小朋友,她的爱好是画画和读书,尤其喜欢 Thomas H. Co rmen 的文章.粟粟家中有一个 R行C 列的巨型书架,书架的每一个位置都 ...

  10. 观光公交(codevs 1139)

    题目描述 Description 风景迷人的小城 Y 市,拥有n 个美丽的景点.由于慕名而来的游客越来越多,Y 市特意安排了一辆观光公交车,为游客提供更便捷的交通服务.观光公交车在第0 分钟出现在1号 ...