Asp.net core dependency injection, asp. netcore

Source: Internet
Author: User

Asp.net core dependency injection, asp. netcore

Recently,. net core can be used across platforms. This is a great thing. In order to catch up with the cross-platform deployment tide two years later, I also joined the learning column. Today I am studying dependency injection, but I found a problem that has plagued me for a long time. Now I am posting it. I hope someone can help me solve it or reply to it.

Background: I tested. net comes with the dependency injection life cycle, a total of three: Transient, Scope, Single three, through a GUID in the interface, but I found that the scope and single each time is the same, and the guid value of the single instance changes every time.

We can see that the scope and Single changes every time the browser refreshes, And the scope changes, that is, every request changes. However, it is incorrect that single is changed every time. You should keep a unique value for the pair.

 

Program. cs code: startup code

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 () // use server serve10. useContentRoot (Directory. getCurrentDirectory () 11. useIISIntegration () // use IIS12. useStartup <Startup> () // use start page 13. build (); // IWebHost14 15 host. run (); // construct the IWebHost16 for the host application // then start it to listen for incoming HTTP requests 17} 18} 19}

Startup. cs File Code

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 ("deleteworkflow. json ", optional: true, reloadOnChange: true) 10. addJsonFile ($ "deleettings. {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=39894017 Public void ConfigureServices (IServiceCollection services) 18 {// define service 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 {// define the middleware 32 33 if (env. isDevelopment () 34 {35 app. useDeveloperExceptionPage (); 36 app. useBrowserLink (); 37 app. useDatabaseErrorPage (); 38 39} 40 else41 {42 app. useExc EptionHandler ("/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 // default route setting 50 app. useMvc (routes => 51 {52 routes. mapRoute (name: "default", template: "{controller = Person}/{action = Index}/{id ?} "); 53}); 54 55 56} 57} 58}

Note that lines 22-26 have registered three instances with different lifecycles: transientService, scopeService, and singleService.

Corresponding interface definition:

 1 namespace CoreStudy 2 { 3     public interface IGuideAppService 4     { 5         Guid GuidItem(); 6     } 7     public interface IGuidTransientAppService:IGuideAppService 8     { } 9     public interface IGuidScopeAppService:IGuideAppService10     { }11     public interface IGuidSingleAppService:IGuideAppService12     { }13 14 }15 16 namespace CoreStudy17 {18     public class GuidAppService : IGuideAppService19     {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,IGuidTransientAppService32     {33 34     }35 36     public class ScopeAppService:GuidAppService,IGuidScopeAppService37     { }38     public class SingleAppService:GuidAppService,IGuidSingleAppService39     { }40 }

The code is simple, but three different implementation classes are defined.

Constructor injection in the controller:

1 namespace CoreStudy. controllers 2 {3 /// <summary> 4 // Controller Method 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 /// constructor 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 // homepage Method 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}

View File Index. cshtm corresponding to the Controller

1 @ {2 ViewData ["Title"] = "Person Index"; 3 Layout = null; 4} 5 6 <form asp-controller = "person" method = "post" class = "form-horizontal" role = "form"> 7 

 

Other irrelevant codes will not be pasted. I hope you can give an explanation. Let's take a look at the code and see if special settings are required.

The answer is in line 35 of the PersonController class. This is mainly to better understand dependency injection.

. Net Core is coming, and we can raise our salary again through learning.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.