asp.net core 自定义中间件【以dapper为例】

在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/qingchengcoding/p/10878721.html