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

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

通过截图可以看到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来了,我们又可以通过学习来涨工资了。

asp.net core 依赖注入问题的更多相关文章

  1. # ASP.NET Core依赖注入解读&使用Autofac替代实现

    标签: 依赖注入 Autofac ASPNETCore ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Aut ...

  2. 实现BUG自动检测 - ASP.NET Core依赖注入

    我个人比较懒,能自动做的事绝不手动做,最近在用ASP.NET Core写一个项目,过程中会积累一些方便的工具类或框架,分享出来欢迎大家点评. 如果以后有时间的话,我打算写一个系列的[实现BUG自动检测 ...

  3. [译]ASP.NET Core依赖注入深入讨论

    原文链接:ASP.NET Core Dependency Injection Deep Dive - Joonas W's blog 这篇文章我们来深入探讨ASP.NET Core.MVC Core中 ...

  4. asp.net core 依赖注入几种常见情况

    先读一篇注入入门 全面理解 ASP.NET Core 依赖注入, 学习一下基本使用 然后学习一招, 不使用接口规范, 直接写功能类, 一般情况下可以用来做单例. 参考https://www.cnblo ...

  5. ASP.NET Core依赖注入——依赖注入最佳实践

    在这篇文章中,我们将深入研究.NET Core和ASP.NET Core MVC中的依赖注入,将介绍几乎所有可能的选项,依赖注入是ASP.Net Core的核心,我将分享在ASP.Net Core应用 ...

  6. 自动化CodeReview - ASP.NET Core依赖注入

    自动化CodeReview系列目录 自动化CodeReview - ASP.NET Core依赖注入 自动化CodeReview - ASP.NET Core请求参数验证 我个人比较懒,能自动做的事绝 ...

  7. ASP.NET Core 依赖注入最佳实践——提示与技巧

    在这篇文章,我将分享一些在ASP.NET Core程序中使用依赖注入的个人经验和建议.这些原则背后的动机如下: 高效地设计服务和它们的依赖. 预防多线程问题. 预防内存泄漏. 预防潜在的BUG. 这篇 ...

  8. ASP.NET Core依赖注入最佳实践,提示&技巧

    分享翻译一篇Abp框架作者(Halil İbrahim Kalkan)关于ASP.NET Core依赖注入的博文. 在本文中,我将分享我在ASP.NET Core应用程序中使用依赖注入的经验和建议. ...

  9. ASP.NET Core依赖注入解读&使用Autofac替代实现【转载】

    ASP.NET Core依赖注入解读&使用Autofac替代实现 1. 前言 2. ASP.NET Core 中的DI方式 3. Autofac实现和自定义实现扩展方法 3.1 安装Autof ...

  10. ASP.NET Core 依赖注入基本用法

    ASP.NET Core 依赖注入 ASP.NET Core从框架层对依赖注入提供支持.也就是说,如果你不了解依赖注入,将很难适应 ASP.NET Core的开发模式.本文将介绍依赖注入的基本概念,并 ...

随机推荐

  1. 百度 flash html5自切换 多文件异步上传控件webuploader基本用法

    双核浏览器下在chrome内核中使用uploadify总有302问题,也不知道如何修复,之所以喜欢360浏览器是因为帮客户控制渲染内核: 若页面需默认用极速核,增加标签:<meta name=& ...

  2. 前端学HTTP之实体和编码

    前面的话 每天都有各种媒体对象经由HTTP传送,如图像.文本.影片以及软件程序等.HTTP要确保它的报文被正确传送,识别.提取以及适当处理.为了实现这些目标,HTTP使用了完善的标签来描述承载内容的实 ...

  3. 用神奇的currentColor制作简洁的颜色动画效果

    先上一个兼容性总结图:老版本ie可以直接用复杂方法了,套用某表情包的话:  2016年了,做前端你还考虑兼容IE6?你这简直是自暴自弃! 好了,知道了兼容性,我们可以放心的使用了. 在CSS3中扩展了 ...

  4. bzoj1901--树状数组套主席树

    树状数组套主席树模板题... 题目大意: 给定一个含有n个数的序列a[1],a[2],a[3]--a[n],程序必须回答这样的询问:对于给定的i,j,k,在a[i],a[i+1],a[i+2]--a[ ...

  5. 【干货分享】流程DEMO-资产请购单

    流程名: 资产请购  业务描述: 流程发起时,会检查预算,如果预算不够,流程必须经过总裁审批,如果预算够用,将发起流程,同时占用相应金额的预算,但撤销流程会释放相应金额的预算.  流程相关文件: 流程 ...

  6. android SystemServer.java启动的服务。

    EntropyService:熵(shang)服务,用于产生随机数PowerManagerService:电源管理服务ActivityManagerService:最核心服务之一,Activity管理 ...

  7. 如何搭建git服务器

    一.前言 现在越来越多的公司用git进行版本控制,不过git是默认是开源的,如果私有的话是需要付费的,如果不想付费自己可以搭建一个git服务器用来版本控制. 二.服务器端操作 1.安装git sudo ...

  8. Windows cmd 长时间不输出新内容 直到按下ctrl + c 取消或者回车的解决办法

    换了一台新电脑, 在使用 ant 拷贝大量文件的时候 cmd 窗口过了很久没有继续输出新的内容,远远超过平时的耗时, 以为已经卡死 按下 ctrl + c 取消, 这时并没有取消, 而是输出了新内容, ...

  9. Android快乐贪吃蛇游戏实战项目开发教程-03虚拟方向键(二)绘制一个三角形

    该系列教程概述与目录:http://www.cnblogs.com/chengyujia/p/5787111.html 一.绘制三角形 在上一篇文章中,我们已经新建了虚拟方向键的自定义控件Direct ...

  10. To Java程序员:切勿用普通for循环遍历LinkedList

    ArrayList与LinkedList的普通for循环遍历 对于大部分Java程序员朋友们来说,可能平时使用得最多的List就是ArrayList,对于ArrayList的遍历,一般用如下写法: p ...