在 ASP.NET core 开发中. 按照国际案例开始. 都是先在 Nuget 安装 XXX 包. 比如我们今天要用到的 Dapper
nuget 里面安装 Dapper
1. 然后新建一个类文件 DapperExtensions.cs
因为 Dapper 是 IDbConnection 扩展出来的, 所以我们必须给 IDbConnection 一个默认的实现
- /// <summary>
- /// 注入服务
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="service"></param>
- /// <returns></returns>
- public static IServiceCollection AddDapper<T>(this IServiceCollection service) where T:class,IDbConnection
- {
- service.AddScoped<IDbConnection, T>();
- return service;
- }
如何使用呢? 在 Startup 里面加入
services.AddDapper();
理论上到这里, 就已经可以勉强使用了. 但是本文是记录中间件的学习, 所以我们还是得在后面学习一下中间件的写法
2. 新建一个 DapperMiddleWareExtensions.cs 和 DapperMiddleWare.cs 文件
- public class DapperMiddleWare
- {
- private readonly RequestDelegate _next;
- private DapperOption _option;
- public DapperMiddleWare(RequestDelegate next, DapperOption option)
- {
- _next = next;
- this._option = option;
- }
- public async Task InvokeAsync(HttpContext context)
- {
- var conn = context.RequestServices.GetService<IDbConnection>();
- if (_option != default(DapperOption))
- {
- if (!_option.connStr.IsNull())
- {
- conn.ConnectionString = _option.connStr;
- }
- }
- // Call the next delegate/middleware in the pipeline
- await _next(context);
- }
- }
- public static class DapperMiddleWareExtensions
- {
- public static IApplicationBuilder UseDapper(this IApplicationBuilder builder, Action<DapperOption> option = null)
- {
- DapperOption opt = new DapperOption();
- if (option != null)
- {
- option(opt);
- }
- return builder.UseMiddleware<DapperMiddleWare>(opt);
- }
- }
使用:
- App.UseDapper(opt =>
- {
- opt.connStr = Configuration["db:mysqlmaster"];
- });
这两段代码非常简单. 就是编写一个 IApplicationBuilder 的扩展方法, 然后再扩展方法里面获取到注入的 IDbconnection 的接口, 然后把委托方法传递进来的默认配置参数赋值进去, 就可以了.
实际上, 也可以在 AddService 的时候就可以把委托配置给赋值进去, 很多第三方的库就是这么做的.
来源: https://www.cnblogs.com/feimaoicoding/p/10878721.html