gpt4 book ai didi

c# - 如何在asp.net core中的startup.cs文件的configure方法中更改作用域服务的属性值

转载 作者:行者123 更新时间:2023-12-03 08:33:38 27 4
gpt4 key购买 nike

我将在startup.cs 文件中更改或插入一些值到我的作用域服务。

这是我的代码。

我正在向 MyService.SomeData 属性插入一个值。但是,在 View 页面中,打印空值。

这是为什么?

Startup.cs

namespace MyProject
{
public class Startup
{
.
.
.
public void ConfigureServices(IServiceCollection services)
{
.
.
.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<MyService>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var scope = app.ApplicationServices.CreateScope();
var MyService = scope.ServiceProvider.GetService<MyService>();
app.Use(async (context, next) =>
{
if (context.Request.Query.ContainKey("conditionKey") && context.Request.Query["conditonKey"] == "something")
{
MyService.SomeData = "foo";
}
});
}
}
}

MyService.cs

namespace MyProject.Service
{
public class MyService
{
public string SomeData { get; set; } = "";
{
}

MyView.cshtml

@inject MyProject.Service.MyService MyService
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>@MyService.SomeData</div>
</body>

最佳答案

ASP.NET Core 管道为每个 http 请求创建作用域,因此您需要在操作方法内设置此属性

public class HomeController : Controller
{
private readonly MyService myService;

public HomeController(MyService myService)
{
this.myService = myService;
}

public IActionResult Index()
{
myService.MyData = "MyData";

return View();
}
}

或者将您的服务注册为单例

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<MyService>();
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var scope = app.ApplicationServices.CreateScope();
var MyService = scope.ServiceProvider.GetService<MyService>();

MyService.MyData = "SomeData";
}

或者注册自定义过滤器并将其集成到管道中

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(x => x.Filters.Add(typeof(MyServiceFilter)));

services.AddScoped<MyService>();
}


public class MyServiceFilter : IActionFilter
{
private readonly MyService myService;

public MyServiceFilter(MyService myService)
{
this.myService = myService;
}

public void OnActionExecuted(ActionExecutedContext context)
{
}

public void OnActionExecuting(ActionExecutingContext context)
{
myService.MyData = "MyData";
}
}

最后,使用app.Use

app.Use(async (context, next) =>
{
if (context.Request.Query.ContainsKey("conditionKey") && context.Request.Query["conditionKey"] == "something")
{
var myService = context.RequestServices.GetService<MyService>();

myService.MyData = "foo";
}

await next();
});

关于c# - 如何在asp.net core中的startup.cs文件的configure方法中更改作用域服务的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64586205/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com