背景:

  本人在一位大佬的Colder框架中看到了这个接口注入,然后呢就想学习一下ioc思想与di设计模式。此写法给我的感觉就是

非常的 优雅 ,优雅永不过时。关于接口注入的概念和ioc和di具体是什么?可以参考下方的推荐的地址学习。话不多说,开撸。

安装:

  打开nuget管理工具,将我下面标红色的包都进行安装(注:千万别安装错了,按照名字不差的安装)

  

使用:

  我们新建一个DI的文件夹,在文件夹中增加一个接口:IDependency.cs

namespace Coldairarrow
{
/// <summary>
/// 注入标记
/// </summary>
public interface IDependency
{ }
}

    先不要问问什么后面会解释。

    后面:其实。。就是这个依赖注入的一个原理吧。根据这个接口去找依赖的实现。

    推荐去这个地址看一下:https://www.cnblogs.com/atomy/p/12834804.html

    好了,继续分别新建Student.cs,StudentRepository.cs,IStudentRepository.cs三个类。StudentRepository.cs里面的具体业务根据需要自行修改,这里是为了测试使用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace ByzkApi
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Graduation { get; set; }
public string School { get; set; }
public string Major { get; set; }
}
}
using Coldairarrow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace ByzkApi
{
public class StudentRepository : IStudentRepository,IDependency
{
public Student Add(Student item)
{
throw new NotImplementedException();
} public bool Delete(int id)
{
throw new NotImplementedException();
} public Student Get(int id)
{
return new Student() { Name = "张三" };
} public IEnumerable<Student> GetAll()
{
throw new NotImplementedException();
} public bool Update(Student item)
{
throw new NotImplementedException();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ByzkApi
{
public interface IStudentRepository
{
IEnumerable<Student> GetAll();
Student Get(int id);
Student Add(Student item);
bool Update(Student item);
bool Delete(int id); }
}

注意:这里好好看一下 StudentRepository 是实现了两个接口分别是 IStudentRepository IDependency(注入标记)

最关键的地方来了,我们打开项目启动的函数Application_Start,然后注入一下接口依赖。

using Autofac;
using Autofac.Extras.DynamicProxy;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using ByzkApi.Controllers;
using ByzkApi.Interface;
using Coldairarrow;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection;
using System.Web.Compilation;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing; namespace ByzkApi
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//初始化Autofac
InitAutofac(GlobalConfiguration.Configuration); AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
} private void InitAutofac(HttpConfiguration config)
{
var builder = new ContainerBuilder(); var baseType = typeof(IDependency); //可以进行筛选如: Where(x => x.FullName.Contains("Coldairarrow"))
var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>()
.ToList(); //自动注入IDependency接口,支持AOP,生命周期为InstancePerDependency
builder.RegisterAssemblyTypes(assemblys.ToArray())
.Where(x => baseType.IsAssignableFrom(x) && x != baseType)
.AsImplementedInterfaces()
.PropertiesAutowired()
.InstancePerDependency()
.EnableInterfaceInterceptors()
.InterceptedBy(typeof(Interceptor)); //注册Controller
builder.RegisterControllers(assemblys.ToArray())
.PropertiesAutowired();
builder.RegisterApiControllers(assemblys.ToArray()).PropertiesAutowired(); //AOP
builder.RegisterType<Interceptor>();
builder.RegisterWebApiFilterProvider(config); var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
AutofacHelper.Container = container;
} }
}

到此为止就已经注入完成了~

使用:

    这个接口注入好了之后可以在普通的Controller使用,也可以在apiController进行使用,分别看一下效果,结束。

  Controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace ByzkApi.Controllers
{
public class HomeController : Controller
{
readonly IStudentRepository repository;
//构造器注入
public HomeController(IStudentRepository repository)
{
this.repository = repository;
} public ActionResult Index()
{ var a = repository.Get(1); ViewBag.Title = a.Name; return View();
}
}
}

  运行结果:

  ApiController:(如果想要多个接口只需要实现接口的时候进行继承IDependency就可)

  

using ByzkApi.Interface;
using Coldairarrow.Web;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Http; namespace ByzkApi.Controllers
{
public class TestApiController : ApiController
{
readonly IStudentRepository repository; public ITest _test { get; }
//构造器注入
public TestApiController(IStudentRepository repository, ITest test)
{
this.repository = repository;
_test = test;
} [HttpGet]
public DataTable test(string sql)
{
repository.Get(1);
var data = _test.GetTest("sql 语句");
//repository.GetTest(sql);
return data;
}
}
}

  运行效果:

  

C# 利用Autofac批量接口注入依赖【学习记录】的更多相关文章

  1. asp.netcore di 实现批量接口注入

    废话少说,先上代码 public static Dictionary<Type, Type[]> GetImpleAndInterfaces(string assemblyName,str ...

  2. Asp.Net Core 中利用QuartzHostedService 实现 Quartz 注入依赖 (DI)

    QuartzHostedService  是一个用来在Asp.Net Core 中实现 Quartz 的任务注入依赖的nuget 包: 基本示例如下: using System; using Syst ...

  3. ASP.NET Core 2.2 WebApi 系列【三】AutoFac 仓储接口的依赖注入

    一.准备工作 通过程序包管理器控制台安装AutoFac: Install-Package Autofac.Extensions.DependencyInjection 创建新类库(.NetCore 2 ...

  4. 基于SqlSugar的开发框架循序渐进介绍(5)-- 在服务层使用接口注入方式实现IOC控制反转

    在前面随笔,我们介绍过这个基于SqlSugar的开发框架,我们区分Interface.Modal.Service三个目录来放置不同的内容,其中Modal是SqlSugar的映射实体,Interface ...

  5. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之九 || 依赖注入IoC学习 + AOP界面编程初探

    更新 1.如果看不懂本文,或者比较困难,先别着急问问题,我单写了一个关于依赖注入的小Demo,可以下载看看,多思考思考注入的原理: https://github.com/anjoy8/BlogArti ...

  6. Spring.NET依赖注入框架学习--入门

    Spring.NET依赖注入框架学习--入门 在学些Spring.net框架之前,有必要先脑补一点知识,比如什么是依赖注入?IOC又是什么?控制反转又是什么意思?它们与Spring.net又有什么关系 ...

  7. Z从壹开始前后端分离【 .NET Core2.2/3.0 +Vue2.0 】框架之九 || 依赖注入IoC学习 + AOP界面编程初探

    本文梯子 本文3.0版本文章 更新 代码已上传Github+Gitee,文末有地址 零.今天完成的绿色部分 一.依赖注入的理解和思考 二.常见的IoC框架有哪些 1.Autofac+原生 2.三种注入 ...

  8. Asp.NetCore3.1版本的CodeFirst与经典的三层架构与AutoFac批量注入

    Core3.1 CodeFirst与AutoFac批量注入(最下面附GitHub完整 Demo,由于上传网速较慢,这里就直接压缩打包上传了) ===Core3.1 CodeFirst 数据库为远程阿里 ...

  9. Spring.NET依赖注入框架学习--简单对象注入

    Spring.NET依赖注入框架学习--简单对象注入 在前面的俩篇中讲解了依赖注入的概念以及Spring.NET框架的核心模块介绍,今天就要看看怎么来使用Spring.NET实现一个简单的对象注入 常 ...

  10. Spring.NET依赖注入框架学习--简介

    Spring.NET依赖注入框架学习--Spring.NET简介 概述 Spring.NET是一个应用程序框架,其目的是协助开发人员创建企业级的.NET应用程序.它提供了很多方面的功能,比如依赖注入. ...

随机推荐

  1. 三款免费强大的SSH工具食用指南

    食用清单 XShell FinalShell Electerm 食用方案 XShell 先说说老牌ssh工具XShell吧,用过很多年,说实话没啥别的毛病挺好用的.不过,还是有些地方有待加强,比如文件 ...

  2. 力扣41(java)-缺失的第一个正数(困难)

    题目: 给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数. 请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案. 示例 1: 输入:nums = [1,2,0 ...

  3. [FAQ] Smart Contract: xxx has not been deployed to detected network (network/artifact mismatch)

    在前端用 web3 与 contract 交互时,需要获取到已部署的 contract 实例进行操作,如果没有获取到就会报此错. 比如如下的 .deployed() 阶段: /* 伪代码 */ con ...

  4. dotnet 已知问题 使用 Directory.EnumerateXXX 方法枚举 C 盘根路径可能错误的问题

    在 dotnet 里面,可以使用 Directory.EnumerateXXX 系列方法进行枚举文件或文件夹.在准备枚举驱动器根路径的文件或文件夹时,可能获取到错误的路径.错误的步骤在于传入的是如 C ...

  5. dotnet OpenXml SDK 形状填充渐变色的主题色

    在 Office 文档的一些有趣的设计,颜色和画刷是可以继承的,这个继承包括了属性的继承.在形状填充里面使用的渐变色是可以一部分属性放在主题里面,主要找到主题里面的画刷,替换掉形状自己定义的内容,才是 ...

  6. 关于Web的欢迎页面的开发设置

    关于Web的欢迎页面的开发设置 每博一文案 命运总是不如人愿.但往往是在无数的痛苦中,在重重的矛盾和艰辛中,才是人成熟起来. 一次邂逅,一次目光的交融,就是永远的合二为一,就是与上帝的契约:总是风暴雷 ...

  7. pikachu靶机练习平台-xss

    第一题:反射性xss(get) 输出的字符出现在url中 第二题:反射性xss(post) 登录后输入<script>alert(1)</script> 第三题:存储型xss ...

  8. HouseParty原创故事全角色关系及主线剧情介绍(最新版)

    这是原创故事的主要的角色的主线及支线剧情的介绍及攻略和注意事项等. 这里的图比哔哩哔哩上的图清楚一点,哔哩哔哩同号:宅猫君007 以上是全角色的关系图 最新版本的游戏下载就在我的网站上:https:/ ...

  9. 如何在局域网内两台电脑上进行webapi的在线调试

    原文地址:https://www.zhaimaojun.top/Note/5475298(我自己的博客) 局域网内WebApi的远程调试方法: 第一步:管理员方式运行Vs并打开需要运行的项目,如果已经 ...

  10. CentOS7离线部署JDK

    一. 下载JDK 官网地址: https://www.oracle.com/java/technologies/downloads/#java18 网盘地址: 链接:https://pan.baidu ...