与AddScoped卡在一个项目中。
然后,为了进行测试,我在Asp.Net Core中创建了一个新的Web应用程序项目,并创建了一个接口以及一个类IMyInfo和MyInfo。它只有一个整数属性mydata和两个方法Increment()和GetData()。“ Increment()”方法仅将值增加1,而“ GetData()”方法将返回属性“ mydata”的值。通过TestingController,我只是执行Increment()方法,然后调用GetData()。
当我使用AddSingleton服务时,它在每次重新加载请求时都提供一个递增的值(即1,2,3,4 ...),但是每次使用AddScoped(而不是AddTransient)时都会得到“ 1”。
不知道我错了吗?
以下是我的所有代码:
我在一个新项目中创建了以下接口和类:
public interface IMyInfo
{
void Increment();
int GetData();
}
public class MyInfo : IMyInfo
{
private int mydata = 0;
public void Increment()
{
mydata++;
}
public int GetData()
{
return mydata;
}
}
然后创建一个TestController:
public class TestController : Controller
{
private readonly IMyInfo myInfo;
public TestController(IMyInfo myInfo)
{
this.myInfo = myInfo;
}
public string Index()
{
myInfo.Increment();
int d = myInfo.GetData();
return d.ToString();
}
}
这是我的启动文件代码:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<IMyInfo, MyInfo>(); // It is not giving me expected result...
//services.AddSingleton<IMyInfo, MyInfo>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Test}/{action=Index}/{id?}");
});
}
}
是的,这是正常现象。
当service声明为Scoped时,它将在每个范围上都有一个新实例,默认情况下,ASP Core会在每个HTTP请求上创建一个新范围,但是您可以自己创建一个范围(如@juunas正确注释)。
每次使用瞬态时,都会有一个新实例。
就像@ Yiyi You所评论的那样,服务寿命文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句