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();
}





 

转载于:https://www.cnblogs.com/indexlang/p/5730056.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值