.Net Core 依賴注入(Dependency injection)
阿新 • • 發佈:2020-10-18
一、簡介
依賴注入是一種實現物件及基合作者或者依賴項之間鬆散耦合的技術;
二、程式碼實現
(1)、定義介面
namespace WebApplication1.Services { public interface IBookService { /// <summary> /// 獲取描述 /// </summary> /// <returns></returns> string GetDescrption(); } }
(2)、實現介面
namespaceWebApplication1.Services { public class BookServices : IBookService { public string GetDescrption() { var desc = "獲取書本描述!"; return desc; } } }
(3)、在 Startup.css ConfigureServices 方法中配置引用
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews();//新增許可權認證 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie( CookieAuthenticationDefaults.AuthenticationScheme, o => { o.LoginPath = new PathString("/Login/Index"); });//第一種方式:呼叫建立一個例項 services.AddTransient<IBookService, BookServices>(); //第二種方式:一個請求域一個例項 services.AddScoped<IBookService,BookServices>(); //第三種方式:單例模式 services.AddSingleton<IBookService,BookServices>(); }
(4)、注入使用
using Microsoft.AspNetCore.Mvc; using WebApplication1.Services; namespace WebApplication1.Controllers { public class BookController : Controller { // 定義介面 private readonly IBookService _bookService; //注入介面 public BookController(IBookService bookService) { _bookService = bookService; } public IActionResult Index() { //呼叫方法 var desc = _bookService.GetDescrption(); return Content(""); } } }
(5)、實驗截圖