• .Net Core 依赖注入(Dependency injection)


    一、简介

      依赖注入是一种实现对象及基合作者或者依赖项之间松散耦合的技术;

    二、代码实现

      (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);
            }
        }
    }
  • 相关阅读:
    linux常见错误1 -> E: 无法获得锁 /var/lib/apt/lists/lock open
    std::ostringstream用法浅析
    (译)C++11中的Move语义和右值引用
    C++11学习笔记(1) Rangebased for loop
    (转)Linux 下压缩与解压.zip和.rar及.7z文件
    (转)linux 查看当前用户及用户所属组别
    ubuntu 源码编译安装cmake2.8.10.2
    开始自学H5前端第一天
    自学H5第二天
    顶部滚动菜单栏
  • 原文地址:https://www.cnblogs.com/gzbit-zxx/p/13835208.html
Copyright © 2020-2023  润新知