依赖注入
依赖注入服务定位
- 创建一个对象,作为构造函数或者方法的参数,传递到程序需要的部分
- 在服务类添加一个静态方法,提供直接访问共享的实例
在中间件中使用服务
public class WeatherMiddleware{
private RequestDelegate next;
private IRespinseFormatter formatter;
public WeatherMiddleware(RequestDelegate nextDelegate,IResponseFormatter respFormatter)
{
next=nextDelegate;
formatter=respFormatter;
}
public async Task Invoe(HttpContext context){
if(context.Request.Path=="/middleware/class")
{
await formatter.Format(context,"Middleware class:It is raining in London");
else
{
await next(context);
}
}
}
}
//在Program.cs中使用
builder.Services.AddSingleton<IResponseFormatter,HtmlResponseFormatter>();
app.UseMiddleware<WatherMiddleware>();
在Endpoint中使用服务
有的端点类中没有构造函数,并且是静态的,情况会比较复杂,有以下几种办法使用依赖
从HttpContext对象中获取服务
public static async Task Endpoint(HttpContext context)
{
IResponseFormatter formatter=context.RequestServices.GetRequiredService<IResponseFormatter>();
await formatter.Format(context,"Endpoint Class:It is cloudy in Milan");
}
使用一个适配函数
可以在端点方法使用接口
public class WeatherEndpoint{
public static async Task Endpoint(HttpContext context,IResponseFormatter formatter)
{
await formatter.Format(context,"Endpoint Class:It is cloudy in Milan");
}
}
public static class EndpointExtensions{
public static void MapWeather(this IEndpointRouteBuilder app,string path)
{
IResponseFormatter formatter=app.ServiceProvider.GetRequiredService<IResponseFormatter>();
app.MapGet(path,context=>Platform.WeatherEndpoint.Endpoint(context,formatter));
}
}
app.MapWeater("endpoint/class");
Filed under: ASP.NET Core,C#,编程 - @ 2022年5月13日 上午11:50