asp.net core 依赖注入问题

时间:2023-03-09 09:35:47
asp.net core 依赖注入问题

最近.net core可以跨平台了,这是一个伟大的事情,为了可以赶上两年以后的跨平台部署大潮,我也加入到了学习之列。今天研究的是依赖注入,但是我发现一个问题,困扰我很久,现在我贴出来,希望可以有人帮忙解决或回复一下。

背景:我测试.net自带的依赖注入生命周期,一共三个:Transient、Scope、Single三种,通过一个GUID在界面展示,但是我发现scope和single的每次都是相同的,并且single实例的guid值每次都会改变。

asp.net core 依赖注入问题asp.net core 依赖注入问题

通过截图可以看到scope和Single每次浏览器刷新都会改变,scope改变可以理解,就是每次请求都会改变。但是single 每次都改变就不对了。应该保持一个唯一值才对。

Program.cs代码:启动代码

 namespace CoreStudy
{
public class Program
{
public static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var host = new WebHostBuilder()
.UseKestrel()//使用服务器serve
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()//使用IIS
.UseStartup<Startup>()//使用起始页
.Build();//IWebHost host.Run();//构建用于宿主应用程序的IWebHost
//然后启动它来监听传入的HTTP请求
}
}
}

Startup.cs 文件代码

 namespace CoreStudy
{
public class Startup
{
public Startup(IHostingEnvironment env, ILoggerFactory logger)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
builder.AddInMemoryCollection(); }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{//定义服务
services.AddMvc();
services.AddLogging();
services.AddTransient<IPersonRepository, PersonRepository>();
services.AddTransient<IGuidTransientAppService, TransientAppService>(); services.AddScoped<IGuidScopeAppService, ScopeAppService>(); services.AddSingleton<IGuidSingleAppService, SingleAppService>();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
{//定义中间件 if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage(); }
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
//app.UseStaticFiles(new StaticFileOptions() {
// FileProvider=new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),@"staticFiles")),
// RequestPath="/staticfiles"
// });
//默认路由设置
app.UseMvc(routes =>
{
routes.MapRoute(name: "default", template: "{controller=Person}/{action=Index}/{id?}");
}); }
}
}

请注意22-26行,注册了三种不同生命周期的实例,transientService、scopeService以及singleService。

对应的接口定义:

 namespace CoreStudy
{
public interface IGuideAppService
{
Guid GuidItem();
}
public interface IGuidTransientAppService:IGuideAppService
{ }
public interface IGuidScopeAppService:IGuideAppService
{ }
public interface IGuidSingleAppService:IGuideAppService
{ } } namespace CoreStudy
{
public class GuidAppService : IGuideAppService
{
private readonly Guid item;
public GuidAppService()
{
item = Guid.NewGuid();
}
public Guid GuidItem()
{
return item;
} }
public class TransientAppService:GuidAppService,IGuidTransientAppService
{ } public class ScopeAppService:GuidAppService,IGuidScopeAppService
{ }
public class SingleAppService:GuidAppService,IGuidSingleAppService
{ }
}

代码很简单,只是定义了三种不同实现类。

控制器中 通过构造函数注入方式注入:

 namespace CoreStudy.Controllers
{
/// <summary>
/// 控制器方法
/// </summary>
public class PersonController : Controller
{
private readonly IGuidTransientAppService transientService;
private readonly IGuidScopeAppService scopedService;
private readonly IGuidSingleAppService singleService; private IPersonRepository personRepository = null;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="repository"></param>
public PersonController(IGuidTransientAppService trsn, IGuidScopeAppService scope, IGuidSingleAppService single)
{
this.transientService = trsn;
this.scopedService = scope;
this.singleService = single;
} /// <summary>
/// 主页方法
/// </summary>
/// <returns></returns>
public IActionResult Index()
{
ViewBag.TransientService = this.transientService.GuidItem(); ViewBag.scopeService = this.scopedService.GuidItem(); ViewBag.singleservice = this.scopedService.GuidItem(); return View();
} }
}

控制器对应的视图文件Index.cshtm

 @{
ViewData["Title"] = "Person Index";
Layout = null;
} <form asp-controller="person" method="post" class="form-horizontal" role="form">
<h4>创建账户</h4>
<hr />
<div class="row">
<div class="col-md-4">
<span>TransientService:</span>
@ViewBag.TransientService
</div>
</div>
<div class="row">
<span>Scope</span>
@ViewBag.ScopeService
</div>
<div class="row">
<span>Single</span>
@ViewBag.SingleService
</div>
<div class="col-md-4">
@await Component.InvokeAsync("Greeting");
</div>
</form>

其他无关代码就不粘贴了,希望各位能给个解释,我再看一下代码,是否哪里需要特殊设置。

答案在PersonController 类的 35行,此问题主要是为了能够更好的理解依赖注入

.Net Core来了,我们又可以通过学习来涨工资了。