asp.net core 依賴註入問題

来源:http://www.cnblogs.com/jiagoushi/archive/2016/09/05/5844097.html
-Advertisement-
Play Games

最近.net core可以跨平臺了,這是一個偉大的事情,為了可以趕上兩年以後的跨平臺部署大潮,我也加入到了學習之列。今天研究的是依賴註入,但是我發現一個問題,困擾我很久,現在我貼出來,希望可以有人幫忙解決或回覆一下。 背景:我測試.net自帶的依賴註入生命周期,一共三個:Transient、Scop ...


     最近.net core可以跨平臺了,這是一個偉大的事情,為了可以趕上兩年以後的跨平臺部署大潮,我也加入到了學習之列。今天研究的是依賴註入,但是我發現一個問題,困擾我很久,現在我貼出來,希望可以有人幫忙解決或回覆一下。

   背景:我測試.net自帶的依賴註入生命周期,一共三個:Transient、Scope、Single三種,通過一個GUID在界面展示,但是我發現scope和single的每次都是相同的,並且single實例的guid值每次都會改變。

通過截圖可以看到scope和Single每次瀏覽器刷新都會改變,scope改變可以理解,就是每次請求都會改變。但是single 每次都改變就不對了。應該保持一個唯一值才對。

 

Program.cs代碼:啟動代碼

 1 namespace CoreStudy
 2 {
 3     public class Program
 4     {
 5         public static void Main(string[] args)
 6         {
 7             Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
 8             var host = new WebHostBuilder()
 9                 .UseKestrel()//使用伺服器serve
10                 .UseContentRoot(Directory.GetCurrentDirectory())
11                 .UseIISIntegration()//使用IIS
12                 .UseStartup<Startup>()//使用起始頁
13                 .Build();//IWebHost
14 
15             host.Run();//構建用於宿主應用程式的IWebHost
16             //然後啟動它來監聽傳入的HTTP請求
17         }
18     }
19 }

Startup.cs 文件代碼

 1 namespace CoreStudy
 2 {
 3     public class Startup
 4     {
 5         public Startup(IHostingEnvironment env, ILoggerFactory logger)
 6         {
 7             var builder = new ConfigurationBuilder()
 8                 .SetBasePath(env.ContentRootPath)
 9                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
10                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
11                 .AddEnvironmentVariables();
12             builder.AddInMemoryCollection();
13 
14         }
15         // This method gets called by the runtime. Use this method to add services to the container.
16         // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
17         public void ConfigureServices(IServiceCollection services)
18         {//定義服務            
19             services.AddMvc();
20             services.AddLogging();
21             services.AddTransient<IPersonRepository, PersonRepository>();
22             services.AddTransient<IGuidTransientAppService, TransientAppService>();
23 
24             services.AddScoped<IGuidScopeAppService, ScopeAppService>();
25 
26             services.AddSingleton<IGuidSingleAppService, SingleAppService>();
27         }
28 
29         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
30         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
31         {//定義中間件
32 
33             if (env.IsDevelopment())
34             {
35                 app.UseDeveloperExceptionPage();
36                 app.UseBrowserLink();
37                 app.UseDatabaseErrorPage();
38 
39             }
40             else
41             {
42                 app.UseExceptionHandler("/Home/Error");
43             }
44             app.UseStaticFiles();
45             //app.UseStaticFiles(new StaticFileOptions() {
46             //      FileProvider=new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(),@"staticFiles")),
47             //       RequestPath="/staticfiles"
48             // });
49             //預設路由設置
50             app.UseMvc(routes =>
51             {
52                 routes.MapRoute(name: "default", template: "{controller=Person}/{action=Index}/{id?}");
53             });
54 
55            
56         }
57     }
58 }

請註意22-26行,註冊了三種不同生命周期的實例,transientService、scopeService以及singleService。

對應的介面定義:

 1 namespace CoreStudy
 2 {
 3     public interface IGuideAppService
 4     {
 5         Guid GuidItem();
 6     }
 7     public interface IGuidTransientAppService:IGuideAppService
 8     { }
 9     public interface IGuidScopeAppService:IGuideAppService
10     { }
11     public interface IGuidSingleAppService:IGuideAppService
12     { }
13 
14 }
15 
16 namespace CoreStudy
17 {
18     public class GuidAppService : IGuideAppService
19     {
20         private readonly Guid item;
21         public GuidAppService()
22         {
23             item = Guid.NewGuid();
24         }
25         public Guid GuidItem()
26         {
27             return item;
28         }
29         
30     }
31     public class TransientAppService:GuidAppService,IGuidTransientAppService
32     {
33 
34     }
35 
36     public class ScopeAppService:GuidAppService,IGuidScopeAppService
37     { }
38     public class SingleAppService:GuidAppService,IGuidSingleAppService
39     { }
40 }

代碼很簡單,只是定義了三種不同實現類。

控制器中 通過構造函數註入方式註入:

 1 namespace CoreStudy.Controllers
 2 {
 3     /// <summary>
 4     /// 控制器方法
 5     /// </summary>
 6     public class PersonController : Controller
 7     {
 8         private readonly IGuidTransientAppService transientService;
 9         private readonly IGuidScopeAppService scopedService;
10         private readonly IGuidSingleAppService singleService;
11 
12 
13         private IPersonRepository personRepository = null;
14         /// <summary>
15         /// 構造函數
16         /// </summary>
17         /// <param name="repository"></param>
18         public PersonController(IGuidTransientAppService trsn, IGuidScopeAppService scope, IGuidSingleAppService single)
19         {
20             this.transientService = trsn;
21             this.scopedService = scope;
22             this.singleService = single;
23         }
24 
25         /// <summary>
26         /// 主頁方法
27         /// </summary>
28         /// <returns></returns>
29         public IActionResult Index()
30         {
31             ViewBag.TransientService = this.transientService.GuidItem();
32 
33             ViewBag.scopeService = this.scopedService.GuidItem();
34 
35             ViewBag.singleservice = this.scopedService.GuidItem();
36 
37             return View();
38         }
39 
40 
41     }
42 }

控制器對應的視圖文件Index.cshtm

 1 @{
 2     ViewData["Title"] = "Person Index";
 3     Layout = null;
 4 }
 5 
 6 <form asp-controller="person"  method="post" class="form-horizontal" role="form"> 
 7      <h4>創建賬戶</h4>
 8     <hr />
 9    <div class="row">
10        <div class="col-md-4">
11            <span>TransientService:</span>
12            @ViewBag.TransientService
13        </div>       
14    </div>
15     <div class="row">
16         <span>Scope</span>
17         @ViewBag.ScopeService
18     </div>
19     <div class="row">
20         <span>Single</span>
21         @ViewBag.SingleService
22     </div>
23     <div class="col-md-4">
24         @await Component.InvokeAsync("Greeting");
25     </div>
26 </form>

 

其他無關代碼就不粘貼了,希望各位能給個解釋,我再看一下代碼,是否哪裡需要特殊設置。

 答案在PersonController 類的 35行,此問題主要是為了能夠更好的理解依賴註入

.Net Core來了,我們又可以通過學習來漲工資了。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Oracle使用正則表達式離不開這4個函數: 1。regexp_like 2。regexp_substr 3。regexp_instr 4。regexp_replace 看函數名稱大概就能猜到有什麼用了。 regexp_like 只能用於條件表達式,和 like 類似,但是使用的正則表達式進行匹配, ...
  • 目錄與路徑 cd:切換目錄 例如:cd ~willhua,則回到用戶willhua的主文件夾 cd ~或者cd,則表示回到自己的的主文件夾 cd -,則表示回到上個目錄 pwd:顯示目前所在目錄 參數: -p,顯示當前路徑,而非使用連接路徑 mkdir:新建新目錄 參數: -m:直接配置文件的許可權, ...
  • [comment]: Docker on CentOS for beginners Introduction The article will introduce Docker on CentOS. Key concepts Docker Docker is the world's leading ...
  • 最簡單的bootloader的編寫步驟: 1. 初始化硬體:關看門狗、設置時鐘、設置SDRAM、初始化NAND FLASH2. 如果bootloader比較大,要把它重定位到SDRAM3. 把內核從NAND FLASH讀到SDRAM4. 設置"要傳給內核的參數"5. 跳轉執行內核 改進:1. 提高C ...
  • Homebrew 是mac上的包管理工具,其官網; http://brew.sh/ 在使用brew安裝node之後安裝一些常見工具比如 gulp 提示安裝成功之後 ,使用發現不存在comman gulp,這個時候我們要檢查下npm全局路徑在哪裡 正常的路徑應該是 /usr/local/lib/nod ...
  • PMP,全稱是Percona Monitoring Plugins,是Percona公司為MySQL監控寫的插件。支持Nagios,Cacti。從PMP 1.1開始,支持Zabbix。 下麵,看看如何在Zabbix上安裝PMP。 配置Zabbix Agent 下載PMP 下載地址:https://w ...
  • ps -ef | grep java ps aux | grep java ps aux 是用BSD的格式來顯示Java進程 顯示的項目有: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND ps -ef 是用標準的格式來顯示Java進程 ...
  • DevExpress中定義的ChartControl很不錯,很多項目直接使用這種控制項。 本節講述雷達圖的樣式設置 <Grid> <Grid.Resources> <DataTemplate x:Key="LabelItemDataTemplate" DataType="dxc:SeriesLabel ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...