一、简介
依赖注入是一种实现对象及基合作者或者依赖项之间松散耦合的技术;
二、代码实现
(1)、定义接口
namespace WebApplication1.Services { public interface IBookService { /// <summary> /// 获取描述 /// </summary> /// <returns></returns> string GetDescrption(); } }
(2)、实现接口
namespace WebApplication1.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)、实验截图
(6)、安装 SqlServer 链接需要的安装包。
首先需要安装 Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.SqlServer
(7)、编写 CommonDbContext.cs
using Microsoft.EntityFrameworkCore; namespace WebApplication1 { public class CommonDbContext : DbContext { public CommonDbContext(DbContextOptions options) : base(options) { } } }
(8)、在 Startup.cs 中添加注入
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>(); services.AddDbContextPool<CommonDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }
(9)、使用 CommonDbContext
using Microsoft.AspNetCore.Mvc; using WebApplication1.Services; namespace WebApplication1.Controllers { public class BookController : Controller { // 定义接口 private readonly IBookService _bookService; private readonly CommonDbContext _commonDbContext; //注入接口 public BookController(IBookService bookService, CommonDbContext commonDbContext) { _bookService = bookService; _commonDbContext = commonDbContext; } public IActionResult Index() { //调用方法 var desc = _bookService.GetDescrption(); return Content(desc); } } }