asp.net core 自定义中间件和service

首先新建项目看下main方法:

复制代码
public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}
main方法
复制代码

其中,UseStartup<Startup>()方法使用了Startup类,在Startup类,有ConfigureServices和Configure方法,调用顺序是先ConfigureServices后Configure。

 

下面生成自定义的Service:

复制代码
public interface IMService
{
    string GetString();
}

public class MService:IMService
{
    public string GetString()
    {
        return "这是我的服务";
    }
}
View Code
复制代码

可以在ConfigureServices中这样使用:

services.AddSingleton<IMService, MService>();
或者
s
ervices.AddScoped<IMService, MService>();
或者
services.AddTransient<IMService, MService>();
这三个方法的作用都一样,只是生成实例的方式不一样,Singleton是所有的service都用单一的实例,Scoped 是一个请求一个实例,Transient 每次使用都是新实例。
也可以使用依赖注入的方式添加服务
复制代码
public static class MServiceExtensions
{
    public static void AddMService(
           this IServiceCollection services)
    {
        services.AddScoped<IMService,MService>();
    }
}
View Code
复制代码

这样就可以在ConfigureServices中这样用:services.AddMService();

 

下面自定义一个middleware

复制代码
    public class MMiddleware
    {
        private RequestDelegate nextMiddleware;

        public MMiddleware(RequestDelegate next)
        {
            this.nextMiddleware = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Items.Add("middlewareID",
                         "ID of your middleware");
            await this.nextMiddleware.Invoke(context);
        }
    }
View Code
复制代码

同样的,可以在Configure方法中这样使用:app.UseMiddleware<MMiddleware>();

也可以

public static class MyMiddlewareExtensions
{
    public static IApplicationBuilder UseMMiddleware
              (this IApplicationBuilder app)
    {
        return app.UseMiddleware<MMiddleware>();
    }
}
就可以app.UseMMiddleware();


在controller中可以
public IActionResult Index()
{
    ViewBag.str= service.Getstring();
    ViewBag.MiddlewareID = HttpContext.Items["middlewareID"];
    return View();
}





 

posted @   indexlang  阅读(3301)  评论(3编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示