1. 定義一個服務,包含一個方法
public class TextService { public string Print(string m) { return m; } }
2. 寫一個擴展方法用來注入服務
using Haos.Develop.CoreTest.Service; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Haos.Develop.CoreTest { public static class Extension { public static IServiceCollection AddTestService(this IServiceCollection service) { return service.AddScoped(factory => new TextService()); } } }
3. 回到Startup類中找到ConfigureServices方法添加如下代碼
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddTestService();//手動高亮 }
4.我們可以采用構造函數方式來使用或者方法用參數的形式注入和直接獲取
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using Haos.Develop.CoreTest.Service; namespace Haos.Develop.CoreTest.Controllers { public class HomeController : Controller { public TextService T; public HomeController(TextService t) { T = t; } public ActionResult Index() { return Content("ok"); } /// <summary> /// 使用構造函數注入 /// </summary> /// <returns></returns> public JsonResult Test() { T.Print("哈哈哈哈哈哈哈哈哈哈哈哈"); return Json(""); } /// <summary> /// 參數注入 /// </summary> /// <param name="t2"></param> /// <returns></returns> public JsonResult Test2(TextService t2) { t2.Print("哈哈哈哈哈哈哈哈哈哈哈哈"); return Json(""); } /// <summary> /// 直接獲取 /// </summary> /// <returns></returns> public JsonResult Test3() { var t3 = HttpContext.RequestServices.GetService(typeof(TextService)) as TextService; t3.Print("哈哈哈哈哈哈哈哈哈哈哈哈"); return Json(""); } } }
5. 如果存在參數可以在構造函數中賦值
示例:
5.1 修改第一點的代碼
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Haos.Develop.CoreTest.Service { public class TextService { public string StrString { get; set; } public TextService(string m) { StrString = m; } public string Print(string m) { return StrString + m; } } }
5.2 修改第二點的代碼
using Haos.Develop.CoreTest.Service; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Haos.Develop.CoreTest { public static class Extension { public static IServiceCollection AddTestService(this IServiceCollection service,string str) { return service.AddScoped(factory => new TextService(str)); } } }
最后注入
public void ConfigureServices(IServiceCollection services) { services.AddTestService("this test param"); }
6 生命周期
6.1 瞬時(Transient)
生命周期服務在它們每次請求時被創建。這一生命周期適合輕量級的,無狀態的服務。
6.2 作用域(Scoped)
作用域生命周期服務在每次請求被創建一次。
6.3 單例(Singleton)
單例生命周期服務在它們第一次被請求時創建並且每個后續請求將使用相同的實例。