首页 > 解决方案 > 使用中间件 ASP.NET 进行依赖注入

问题描述

我有办法编写一些代码来使用中间件在屏幕上获取当前时间。我有下一节时间服务

public class TimeService
{
    public TimeService()
    {
        Time = DateTime.Now.ToString("hh:mm:ss");
    }
    public string Time { get; }
}

和下一个 TimerMiddleware 类

public class TimerMiddleware
{
    private readonly RequestDelegate _next;
    TimeService _timeService;

    public TimerMiddleware(RequestDelegate next, TimeService timeService)
    {
        _next = next;
        _timeService = timeService;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (context.Request.Path.Value.ToLower() == "/time")
        {
            context.Response.ContentType = "text/html; charset=utf-8";
            await context.Response.WriteAsync($"Current time: {_timeService?.Time}");
        }
        else
        {
            await _next.Invoke(context);
        }
    }
}

现在我的启动类看起来像这样:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<TimeService>();
    }
    public void Configure(IApplicationBuilder app)
    {
        app.UseMiddleware<TimerMiddleware>();
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync();
        });
    }
}

我应如何修改“启动”类中的“运行”方法以在屏幕上显示时间?

标签: asp.netdependency-injectionmiddleware

解决方案


推荐阅读