網(wǎng)站首頁 編程語言 正文
背景:
本人在一位大佬的Colder框架中看到了這個接口注入,然后呢就想學(xué)習(xí)一下ioc思想與di設(shè)計模式。此寫法給我的感覺就是
非常的 優(yōu)雅 ,優(yōu)雅永不過時。關(guān)于接口注入具體是什么可以最后推薦的地址。話不多說,開擼。
安裝:
打開nuget管理工具,將我下面標紅色的包都進行安裝(注:千萬別安裝錯了,按照名字不差的安裝)
使用:
我們新建一個DI的文件夾,在文件夾中增加一個接口:IDependency.cs
namespace Coldairarrow { /// <summary> /// 注入標記 /// </summary> public interface IDependency { } }
先不要問問什么后面會解釋。
后面:其實。。就是這個依賴注入的一個原理吧。根據(jù)這個接口去找依賴的實現(xiàn)。
推薦去這個地址看一下:https://www.jb51.net/article/206284.htm
好了,繼續(xù)分別新建Student.cs,StudentRepository.cs,IStudentRepository.cs三個類。StudentRepository.cs里面的具體業(yè)務(wù)根據(jù)需要自行修改,這里是為了測試使用。
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 是實現(xiàn)了兩個接口分別是 IStudentRepositoryIDependency(注入標記)
最關(guān)鍵的地方來了,我們打開項目啟動的函數(shù)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; } } }
到此為止就已經(jīng)注入完成了~
使用:
這個接口注入好了之后可以在普通的Controller使用,也可以在apiController進行使用,分別看一下效果,結(jié)束。
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; //構(gòu)造器注入 public HomeController(IStudentRepository repository) { this.repository = repository; } public ActionResult Index() { var a = repository.Get(1); ViewBag.Title = a.Name; return View(); } } }
ApiController:(如果想要多個接口只需要實現(xiàn)接口的時候進行繼承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; } //構(gòu)造器注入 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; } } }
原文鏈接:https://www.cnblogs.com/BFMC/p/15739371.html
相關(guān)推薦
- 2022-07-25 C#爬蟲基礎(chǔ)之HttpClient獲取HTTP請求與響應(yīng)_C#教程
- 2023-05-31 Pandas.DataFrame刪除指定行和列(drop)的實現(xiàn)_python
- 2023-07-27 TypeScript類和多態(tài)、抽象類、訪問修飾符
- 2022-08-11 C++超詳細講解強制類型轉(zhuǎn)換的用法_C 語言
- 2024-02-17 阻塞IO、非阻塞IO、IO多路復(fù)用、AIO的區(qū)別
- 2023-09-12 spring webflux配置成tomcat的線程池
- 2022-08-10 對WPF中的TreeView實現(xiàn)右鍵選定_C#教程
- 2023-01-28 Python多線程與同步機制淺析_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支