asp.net core 自訂中介軟體和service

來源:互聯網
上載者:User

標籤:

首先建立項目看下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();}





 

asp.net core 自訂中介軟體和service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.