.NET Core Console App with Dependency Injection, Logging, and Settings

แชร์
ฝัง
  • เผยแพร่เมื่อ 2 ต.ค. 2024

ความคิดเห็น • 696

  •  4 ปีที่แล้ว +238

    When I see the "I" in the channel's name, I always think it's an interface.

    • @MarioMaletic
      @MarioMaletic 4 ปีที่แล้ว

      lol

    • @YoloMonstaaa
      @YoloMonstaaa 4 ปีที่แล้ว +1

      Truuue

    • @lborate3543
      @lborate3543 4 ปีที่แล้ว

      Lol so true.

    • @ibrahimhussain3248
      @ibrahimhussain3248 4 ปีที่แล้ว +16

      public class Myself: IAmTimCorey
      {
      // Now I can do whatever Tim can do...
      }

    • @ericjalbert9433
      @ericjalbert9433 4 ปีที่แล้ว +1

      @@ibrahimhussain3248 For that you should derive the implementation rather than just implementing the interface... because you could say Throw new UnimplimentedMethodException() for each method.... lol

  • @ibrahimhussain3248
    @ibrahimhussain3248 4 ปีที่แล้ว +49

    Yes. I would very much like to see the winforms and WPF version of this.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +12

      I will add it to the list. Thanks for the suggestion.

    • @Kevin-mb4xf
      @Kevin-mb4xf 3 ปีที่แล้ว

      @@IAmTimCorey I would love that too. I started with the TimCo video of appsettings, but since I didn't finish the entire TimCo Video list, I didn't have any of the coding in place that you altered, which made it abracadabra for me. :) This video is awesome, am curious how well this translates to WPF project (from scratch). :D
      Thank you for making the time to making this video!

  • @lockegarmin4615
    @lockegarmin4615 4 ปีที่แล้ว +7

    Good video. Just a couple clean up items that were forgotten:
    1. *host* is an IDisposable, so you should wrap it in a using in your main method or call Dispose() manually. This way it cleans up every dependency that you might have living in your dependency injection.
    2. It's best practice to call Serilog's Log.CloseAndFlush() method at the end of your program since you created the logger outside of the hosting environment. If you configure Serilog in the .UseSerilog() method, you don't have to do this (assuming you are disposing host properly).

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +4

      You are right. I meant to include the CloseAndFlush at the end and totally forgot to come back to it. Thanks for pointing these out.

  • @RobertOspara
    @RobertOspara 2 ปีที่แล้ว +1

    Great tutorial :-) Tim treats wachers as human beings: inteligent and smart, because he is very inteligent and smart and tries to predict eventual question or request and imediatelly answer to it. What a great guy :-) But without self-exaltation.

    • @IAmTimCorey
      @IAmTimCorey  2 ปีที่แล้ว

      I appreciate the kind words.

  • @parko1965
    @parko1965 2 ปีที่แล้ว

    Tutorials like these are little gems from this man.

  • @TheJessejunior
    @TheJessejunior 4 ปีที่แล้ว +17

    uowwww!!! great content as always, tim!!
    my skills have grown so much since i´ve started following your videos, I usualy watch them several times and they´re my first consulting material whenever I get doubts during daily job....

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +3

      I am glad my content has been so helpful.

  • @lambda-snail
    @lambda-snail 3 ปีที่แล้ว

    When you talked about how reading the error message helps, I remembered some really bad moments I have had with a certain C++ compiler xD I think the C# compiler generally does a good job though, as you say, so that's a relief. Thank you for the video, it's great as usual :)

  • @simoncampbell-smith6745
    @simoncampbell-smith6745 3 ปีที่แล้ว +8

    Great Video Tim, One question, when the service creates the instance of GreetingService How does it know what values to set the constructor parameter objects to? Can you specify them?

  • @dyakobaram
    @dyakobaram 4 ปีที่แล้ว +11

    Recently I found out you are Microsoft MVP can you tell us about that? Like how you became one or what are benefits of being a MVP

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +2

      I will add it to the list. Thanks for the suggestion.

  • @michaelday6987
    @michaelday6987 4 ปีที่แล้ว

    Serilog is all we use where I work. I remember when I first started working professionally, I had to learn how to write a "REAL" console app, because the insurance industry is loaded with EOD console apps. All I was used to was beginner tutorials, and they are used much different in the real world.

  • @flaviodalpino504
    @flaviodalpino504 3 ปีที่แล้ว +7

    Hello Tim ! Thanks for another helpful and great video. At 52:24 you chose CreateInstance but wouldn't it be better to use GetServiceOrCreateInstance that accepts the interface as well ? It makes more sense as the advantage of DI is to predetermine what concrete class to use in the services configuration at line 31 making it easy to choose another concrete class right ?

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว +4

      Yep, that would have been a good choice.

  • @hamidrezaashkiyan
    @hamidrezaashkiyan 4 ปีที่แล้ว +1

    It's funny, I just needed this and you posted a video about it. AMAZING!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      Hope you enjoyed it!

    • @fernandopelacini5662
      @fernandopelacini5662 3 ปีที่แล้ว

      @@IAmTimCorey Same but for a Windows application so doing some changes after watching video

  • @JonHarrison33
    @JonHarrison33 3 ปีที่แล้ว +1

    Not sure if this has already been discovered, but (at least in .NET Core 3.1) when calling i.e.:
    var client = ActivatorUtilities.CreateInstance(host.Services);
    this overwrites our configuration 'builder' object. For example, appsettings.Development.json is unavailable following the 'CreateInstance' call, even though our ASPNETCORE_ENVIRONMENT is set to 'Development.' Only defaults 'appsettings.json' and 'appsettings.Production.json' were available.
    Fix: Passing in 'builder':
    var client = ActivatorUtilities.CreateInstance(host.Services, builder.Build());
    Would love if someone could confirm.
    Thanks again Tim for the great content.

  • @seijumimurasakibara5516
    @seijumimurasakibara5516 2 ปีที่แล้ว

    thank you for the thorough and well explained video! you just earned yourself a new subscriber :) more power to u sir!

  • @michaelestrinone2111
    @michaelestrinone2111 4 ปีที่แล้ว +12

    I always wonder - how do you, Mr.Corey, find these extensions out of thousands available? What is the strategy ? Sort by download count?

    • @TheJohndward01
      @TheJohndward01 4 ปีที่แล้ว

      Same here

    • @morphx666
      @morphx666 4 ปีที่แล้ว

      I was asking myself the exact same thing!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +18

      I read other peoples' code mainly. I see how other people approach a problem and then I take the best parts of what they do and I mix those with the best parts of other projects I have seen. The more code I read, the more perspective I get on useful libraries. This sounds like a great Dev Questions topic. I'll add it to the list.

  • @WarnerBrosers
    @WarnerBrosers 4 ปีที่แล้ว +6

    Hello, Tim. You asked about what we want to see on your channel. So what about signalr core. I fight with this library several mounths, but I can't understand how to implement relations between xamarin forms client and signalr core server hub. I can't understand how to implement authentication by jwt token with asp identity and how to process authorized requests to hub methods on server. I need to use web api technology. Thank you for any attention to my comment.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      That is high on my list of topics to cover. Thanks for the suggestion.

    • @WarnerBrosers
      @WarnerBrosers 4 ปีที่แล้ว

      @@IAmTimCorey thanks for your answer. But I'm already did it)) and I'm so happy. Now I need help with implementing ssl sertificates for asp core app on external hosting. But I don't thing that it is much harder. Thank you.

  • @JonathanPeel
    @JonathanPeel 4 ปีที่แล้ว +5

    I especially enjoyed this video.
    I enjoy most of these videos, but I especially enjoyed this one.
    It is greater to watch this, even if you never intend to write a console app, and explains the DI that gets used when writing an ASP/Web app.
    I really like how you will always say "Don't do this in production" and then go back and fix it.
    It can get a little frustrating when going through tutorials that say things like that, but never show you how to actually do it 'properly'.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Yeah, it is convenient to shortcut things since they aren't the purpose of the video, but I hate that too.

  • @Azcane
    @Azcane 4 ปีที่แล้ว +6

    Great video, as always. Just a small nitpick.
    I wouldn't recommend choosing "Copy always" as a copy option for a file. This forces the project to rebuild every time you build or start the application. This is especially annoying in libraries as they and their dependencies will always be rebuild instead of only when the content of any file changes. "Copy if newer" will almost always suffice except in special cases with dynamically generated files.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Thanks for sharing.

  • @skanyer
    @skanyer 4 ปีที่แล้ว +3

    It looks like the builder object is similar to what CreateDefaultBuilder is doing. You're only using it for Serilog. Couldn't you grab the IConfiguration from the service provider in host and omit the builder object?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +2

      Good question and I wasn't as clear here as I should have been. We need to grab the config file before the Host is set up so that we can log any errors that occur when setting up the host. That's why we manually set it up instead of waiting for the host and getting it then.

  • @gaborbellak5189
    @gaborbellak5189 4 ปีที่แล้ว +4

    Really appreciate your videos Tim!
    Just a remark: I followed this tutorial but I got an error related to "UseSerilog()".... "ihostbuilder' does not contain a definition for 'UseSerilog'
    I had to also install Nuget package: Serilog.AspNetCore to make it work.

  • @Tolg
    @Tolg 3 ปีที่แล้ว +4

    It would be awesome if you could do a video on how we would best create Unit Tests for such a project and test the services that are expecting the ILogger and IConfiguration to be dependency injectected.

    • @tomthelestaff-iamtimcorey7597
      @tomthelestaff-iamtimcorey7597 3 ปีที่แล้ว

      Tim has done multiple videos on Testing, but I will add the suggestion to his list. Explore these to see if they address what you need - th-cam.com/users/IAmTimCoreysearch?query=test

  • @danielweaver6110
    @danielweaver6110 4 ปีที่แล้ว +6

    Great video. I think showing how it is used in a WPF MVVM app would be great as well.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Thanks for your vote.

    • @tinoh.4573
      @tinoh.4573 3 ปีที่แล้ว

      Realy great video! I would like to see a WPF example too. Thank you!

  • @sunilanthony17
    @sunilanthony17 4 ปีที่แล้ว +5

    Tim, this is pure gold:
    var svc = ActivatorUtilities.CreateInstance(host.Services);
    Save my life on a few console application that I'm now refactoring to hookup DI properly or the right way. Thanks a bunch.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      You are welcome.

    • @iambhanu7
      @iambhanu7 4 ปีที่แล้ว +1

      Can you please explain :Why cant we we get the instance of ServiceCollection, then a ServiceProvider and use the "GetService" method on it to get the instance of the GreetingService.

    • @chursee
      @chursee 4 ปีที่แล้ว +1

      Yes that should work like this:
      var svc = host.Services.GetService();

  • @sanelem777
    @sanelem777 4 ปีที่แล้ว +1

    Instead of ActivatorUtilities, I use
    var serviceProvider = services.BuildServiceProvider();
    var greetingMessage = serviceProvider.GetService().Run();
    I can then get instances of all registered services using serviceProvider

  • @oncalldev
    @oncalldev 4 ปีที่แล้ว +5

    As always a very clear, tight explanation of how things work in the .NET world. Thanks.

  • @jalvrus
    @jalvrus 4 ปีที่แล้ว +3

    Thanks for the underscore tip; that will save me some time. I recently implemented something like this using AddHostedService to register the operation class (GreeterService in your case), and host.RunAsync to execute it. The trick with this approach is to call IHostApplicationLifetime.StopApplication at the end of the operation to terminate the process.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      Great tip! Thanks for sharing

  • @oscarjr2088
    @oscarjr2088 3 ปีที่แล้ว +3

    Thank you so much for this!! I discovered this video after struggling with migrating some code from the Framework to Core. The video demonstrated the functionality in a way that I could easily internalize and use. Subscribing to the Patreon is the least I can do. Be well!!!

  • @nacertabib3158
    @nacertabib3158 4 ปีที่แล้ว

    Hello Tim, I really appreciate what you do. is it possible please to do some videos about the internals of technologies in order to learn what is behind the magic. Thank you

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I will add it to the list. Thanks for the suggestion.

  • @olaafr
    @olaafr 3 ปีที่แล้ว +1

    Hey Tim, these videos are great! I subscribe to your paid programs, too! I'm running into an issue integrating this concept in a WPF application that I'm packaging using the MSIX installer. When it's installed in ProgramFiles\WindowsApps, the app (the shortcut on the desktop, or the icon in the start menu) cannot start because it's unable to access the appsettings.json file. It throws an error in the event viewer about this- super easy to reproduce.
    However, if I drill into the WindowsApps folder, and run the .exe directly, it launches. Weird!
    So, I figured I would make a directory in C:\MyApp\Settings\appsettings.json, but the builder seems to refuse to go there:
    builder.SetBasePath(Directory.GetDirectoryRoot("C:\\")).AddJsonFile("MyApp\\Settings\\appsettings.json", false, true);
    Any ideas on what to do?

  • @schh486
    @schh486 4 ปีที่แล้ว +2

    I would love to see a continuation of gRPC that goes more in depth, i cant really seem to find any good advanced guides for c# on gRPC including things like Authentication, Authorization, Security, sending caller information metadata, logging etc etc. That would be great! Thanks for all the great stuff you put out, i was just working in my brand spanking new gRPC console app and thought, hmm how do i get dependecy injection working and i found this :)

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I will add it to the list. Thanks for the suggestion.

  • @Mimmsanfrostborned
    @Mimmsanfrostborned 3 ปีที่แล้ว +1

    When you create the "GreetingsService instance" into svc where do you pass the constructor variables(log and config)?

  • @divanvanzyl7545
    @divanvanzyl7545 4 ปีที่แล้ว +3

    Bro your videos are AMAZING. You are covering the topics that we want to learn about, but other people are not covering!

  • @Suriprofz
    @Suriprofz 3 ปีที่แล้ว +1

    I would recommend to also use '.AddUserSecrets' and use "secrets" instead of appsettings.json, because you don't want any secret keys ending op in your git repo.
    Also might consider:
    var svc = host.Services.GetRequiredService(); instead of using concrete type at CreateInstance();
    Nice video besides that.

  • @tomjones984
    @tomjones984 3 ปีที่แล้ว +7

    I'm liking the videos, very informative! My only gripe is that you elaborate a bit too much on simpler topics when the subject suggests a more advanced user.
    E.g. in this particular video you're looking at more complex things such as DI, but you're also guiding viewers through how to add packages and using statements, and basic Visual Studio usage which I don't think is necessary for more advanced topics and drags out the video length unnecessarily.
    If you haven't done one already, I recommend making a separate video specific to these basic setup/IDE-specific features, which you could then simply reference as and when required.

    • @tomthelestaff-iamtimcorey7597
      @tomthelestaff-iamtimcorey7597 3 ปีที่แล้ว +5

      Thanks for the feedback. Tim believes in giving context for what he is teaching and that takes time. His goal is not entertainment or just to dump knowledge on you but true education. Its a constant balancing act and your feedback helps.

  • @MayronWoW
    @MayronWoW 11 หลายเดือนก่อน

    I'm confused on whether to use `CreateApplicationBuilder` or `CreateDefaultBuilder` in .NET 7. Maybe an updated version of this video is needed to include the newer design in .NET 7?

  • @ibrahimhussain3248
    @ibrahimhussain3248 4 ปีที่แล้ว +2

    The only thing I'm struggling with nowadays is change tracking. It's really hard for me to do that.
    The context.Save() method in EF is very tempting for just this reason

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      If you are tracking changes in a model, you should have a set command for each property. Use that to track changes.

  • @giorgos6576
    @giorgos6576 4 ปีที่แล้ว +1

    Hey Tim maybe make a video for how to use MVP or MVC on win forms?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      I will add it to the list. Thanks for the suggestion.

    • @giorgos6576
      @giorgos6576 4 ปีที่แล้ว

      @@IAmTimCorey Thanks a lot .

  • @jwalkerjr
    @jwalkerjr 4 ปีที่แล้ว +1

    I love using strongly typed access to settings, like Settings.Default.. Is there anything out there that will convert appsettings.json to a strongly-typed object dynamically in Visual Studio? I can imagine a big project with lots of settings and this getting difficult to use. Apologies if you've addressed this elsewhere in the comments. Awesome videos!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +2

      Check out the Options pattern: docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-3.1
      I cover that in my new course: www.iamtimcorey.com/p/net-core-appsettings-in-depth (on sale using the coupon code Celebrate2020 through the end of September).

  • @normannavicom
    @normannavicom ปีที่แล้ว

    Thanks Tim Corey. I would like to know whether its possible to have live sessions with you for learning purposes and consultations where I can ask questions

    • @IAmTimCorey
      @IAmTimCorey  ปีที่แล้ว +1

      Unfortunately, I just don't have the time at this point.

    • @normannavicom
      @normannavicom ปีที่แล้ว

      @@IAmTimCorey can I reach via email?

  • @conaxlearn8566
    @conaxlearn8566 3 ปีที่แล้ว +2

    25:54 I totally agree! It was so pointless to look at Microsoft documentations a few years back. Now they even have little walkthrough tutorials, although for me to read the documentations can sometimes be a bit overwhelming. So tutorial videos like yours are still very precious. 😅

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว +1

      I'm glad I'm able to add to the body of knowledge.

  • @iampaddyofficial
    @iampaddyofficial 4 ปีที่แล้ว +1

    Hi Tim,
    For the EF Core migration to work with the ConsoleApp using DI, we need to add a method public static IHostBuilder CreateHostBuilder(string[] args){} in the Program.cs

  • @reecechannel2013
    @reecechannel2013 3 ปีที่แล้ว +1

    Tip: the error at 52:30 that is show can be fixed by using the GetServiceOrCreateInstance() function with the same input parameter and type as on screen, like so--> var svc = ActivatorUtilities.GetServiceOrCreateInstance(host.Services);

  • @wendyslittleprogram3984
    @wendyslittleprogram3984 4 ปีที่แล้ว +1

    Hey Tim, on an unrelated note, have you considered offering your courses on a subscription model? I think many many people would sign up in a heartbeat. Although your current model may already be working fine!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      I do offer a subscription model. The All Access Pass gives people access to all of the public courses on IAmTimCorey.com for a monthly fee. I open access to sign up every couple of months. Registration will actually be opening soon, so make sure you are on the mailing list so you are alerted when it opens. It only stays open for a few days.

    • @wendyslittleprogram3984
      @wendyslittleprogram3984 4 ปีที่แล้ว

      @@IAmTimCorey my bad, i'll be waiting for that email then!

  • @marcouitendaal985
    @marcouitendaal985 18 วันที่ผ่านมา

    spent most of yesterday figuring out how to use configuration in a console app, including the build option of the appsettings file to 'copy if newer'
    then i was wondering, how could I make dependency injection work in a class that's being instantiated through the console.
    I figured that it must be some kind of host that hovers over everything, cuz how could .Net do it otherwise, but how to have it active in a console?
    And this morning this precise video showed up. An hour well spent.
    I've been messing with .Net courses on Udemy, but yours is next on the list!

  • @pauldechampignon2287
    @pauldechampignon2287 3 ปีที่แล้ว

    I got one problem with the appsettings.{environment}.json. Despite the fact I added "ASPNETCORE_ENVIRONMENT" variable and set is as Development and configuring IConfigurationBuilder( .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)) when I check what is my current environment by checking HostBuilderContext.HostingEnvironment it is still set to Production. I have checked launchsettings.json and over there I got Development as per my variable. Having this when I try to access config variables from my json files it checks only appsettings.json and appsettings.Production.json. I am not sure what's might be going on here?
    I need to mention that if I set up Serilog both in Development and Production settings.json it works fine in updating settings of the logger if I change Environment Variable yet json file taken to configuration is always Production one.

  • @abbyroad8808
    @abbyroad8808 3 ปีที่แล้ว

    Excellent!, but what if you have another class, lets say "ToDo" that have several methods (makeDinner(), buyStuffs()..). Those methods are call from GreeetingService. How can I inject the logging dependency to the "ToDo" list so I can log from there( I would like to do something like GreeetingService {
    ToDo td = new ToDo(ILogger log);

  • @wolfgangdiemer2511
    @wolfgangdiemer2511 3 ปีที่แล้ว

    Hello Tim, great video.
    But here (th-cam.com/video/GAOCe-2nXqc/w-d-xo.html) you said, you will read the appsetting.json from the your directory, where the application (exe) is stored.
    But with Directory.GetCurrentDirectory() you will get the working directory. If you start your application, by double clicking in the windows explorer, you working directory will be system32 by default, you will get in "trouble".

  • @pmclinn
    @pmclinn 4 ปีที่แล้ว +1

    If this was the first video I watched in this channel it would of been the last. I have found previous videos to be more explanatory- as to the why you would do this in the first place? Why on earth wouldn't a simple logging class replace this overhead? I appreciate the content, but feel this is out of scope with the previous training in that it makes leaps and assumptions about users’ underlying experience with these classes. Can you you recommend other videos that may demonstrate use cases.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I can't start every tutorial from square one. Some have to be built upon previous ones. In this case, I'm not sure which piece you are missing - dependency injection (and why it is important) or logging (and why it is important). I have videos on both. Let's start with DI:
      Dependency Inversion Principle: th-cam.com/video/NnZZMkwI6KI/w-d-xo.html
      Dependency Injection: th-cam.com/video/mCUNrRtVVWY/w-d-xo.html
      And here is logging:
      Logging with log4net: th-cam.com/video/2lAdQ_QwNww/w-d-xo.html
      Logging in .NET Core: th-cam.com/video/oXNslgIXIbQ/w-d-xo.html
      Logging with Serilog: th-cam.com/video/_iryZxv8Rxw/w-d-xo.html

  • @PrisonerZ3RO
    @PrisonerZ3RO 2 ปีที่แล้ว

    Do you happen to know a clean way to get console app to return the ClaimsPrincipal or CurrentPrincipal?
    My current sample always returns null.
    I'm sure there is some sort of setup for this...I just don't know it yet...and I'm having a hard time finding any examples online.
    Why would I want this?
    For example, I have a Scheduled Task that imports data...and I am required to show the ServiceAccount in the databases audit (columns)

  • @bblair2010
    @bblair2010 3 ปีที่แล้ว

    I have figured out how to get the method name in the log, by using the following link: stackoverflow.com/questions/29470863/serilog-output-enrich-all-messages-with-methodname-from-which-log-entry-was-ca. However, this does not work for dependency injection when using a general type for logging with the GettingService class. How can I get this to work for DI? By they way, I want to do this for C# for .NET, not VB as shown early in the example.
    I do have a hack, to do this for each method, and it is by using the code snippet below... This not an elegant solution, and I will like to do this correctly for DI by using Serilog.Ilogger and not microsoft.extension.ilogger.
    //Used to get the method name for logging.
    var stackTrace = new System.Diagnostics.StackTrace();
    var name = stackTrace.GetFrame(0).GetMethod().Name;
    //The first thing to gett logged in the application.
    Log.Logger.Information("{name} --> Application Starting.",name);

  • @vssrikanthgarnepudi5952
    @vssrikanthgarnepudi5952 4 ปีที่แล้ว +1

    If possible Can you please make a small video on diff bw Singleton, Transient, Scoped.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      I will add it to the list. Thanks for the suggestion.

  • @MrKaviraj75
    @MrKaviraj75 4 ปีที่แล้ว +1

    Hi Tim
    I really appreciate you doing ML.NET in C#. There are very few tutorials out there, and they are not explaining things well as you. Hope you do ML.NET series :)

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I will add it to the list. Thanks for the suggestion.

  • @Foodies-pv7ih
    @Foodies-pv7ih 4 ปีที่แล้ว +6

    i would like you to talk about .Net 5 as is releases in november, and specially performance imrovements point of view
    thanks

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      I will add it to the list. Thanks for the suggestion.

  • @tommyoman5309
    @tommyoman5309 3 ปีที่แล้ว +1

    I 'm as always impressed of your generosity to share knowhow this way. Thanks!
    I am using autofac in a winforms solution (Net Core) and i'm a little confused over how to handle a case where a window starts another window;
    How would i setup such a scenario , as of now i have an IContainer defining the dependencies but these are resolved in the first window at application.Run.
    And would'nt i change from Autofac to native Microsoft extensions instead ? These are questions that would be interesting to get answers about.
    Or perhaps you have already discussed such questions somewhere ?

    • @dermeister314p
      @dermeister314p 2 ปีที่แล้ว

      I have the same question... Tim has a video about autofac.. as his favourite, but that video and this one, does not exactly add up in the structure setup

  • @goonyahgoodthing7107
    @goonyahgoodthing7107 2 ปีที่แล้ว

    Great Video, thank you.
    Just wondering how command line args could be included in the app to allow users supply params on the command line.
    I tried running it with LoopTimes=42 in the Application Arguments in the debugger but it ignored it... I thought the command line automatically took precendece?
    Thanks

  • @zihasz5305
    @zihasz5305 3 ปีที่แล้ว +2

    Would love to see this but for WinForm apps with maybe file logging.
    Thanks in advance!

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว +1

      Noted! Added to the list

    • @zihasz5305
      @zihasz5305 3 ปีที่แล้ว

      @@IAmTimCorey I really love the vids, they are helpful, easy to understand and useful. Also your quick responses make you AMAZING! Thank you for your great content!

  • @foonlam7134
    @foonlam7134 2 ปีที่แล้ว

    when I type builder.SetBasePath(), I get the error "IConfiguration" does not contain a definition for "SetBasePath". Seems like there is no such method in IConfiguration anymore. What should we substitute it with?

  • @matthiasauswoger7994
    @matthiasauswoger7994 3 ปีที่แล้ว

    Why did you use the ActivatorUtilities class to create the instance of the GreetingService and register the IGreetingService as a service in the DI container?
    With the ActivatorUtilities the registration of the IGreetingService becomes useless, and with using IServiceProvider.GetService() you wouldn't need to use the concrete type.

  • @philipjohndekock
    @philipjohndekock 2 ปีที่แล้ว

    Thanks for the brilliant tutorial, super helpful. I just wanted to know what it the best practice for classes who need to assess the creating of the services to have access to the relevant IServiceProvider. do I just create a class somewhere and copy the reference (of the IHost/IServiceProvider) just after I created it to that class or is there smarter way to derive the exiting IServiceProvider or the IHost from the system somehow. I want the determination of what IServiceProvider to use independent of the Consol app or my MAUI app

  • @Wyliewag
    @Wyliewag ปีที่แล้ว

    I get an error that I cant figure out when using ILogger logger in di in MyClass error: The non-generic type ILogger cannot be used with type arguments. Im not sure what to do, im using .net 6.

  • @omw9965
    @omw9965 3 ปีที่แล้ว

    I searched for Make Console Services list and this came up, how can I make a list of windows services I enable and disabled in an easy way. Instead of wrinting 100s of services listed. Is there an App or any way I can do this in seconds??? Or a minute or two?

  • @goodoleme747
    @goodoleme747 3 ปีที่แล้ว +1

    I’m happy to see this. I’m a developer who primarily works on windows worker services / windows services, and a lot of backend applications where there is no user interaction. A lot of people forget that there are a whole realm of developers who aren’t primarily working on web.

  • @shashankkhandelwal3514
    @shashankkhandelwal3514 4 ปีที่แล้ว +1

    Hi Tim 🙋‍♂️
    I really love the way you explain.
    I have a request. Can you make a series on different types design patterns. I know we already have one video for singleton design patterns but there are other too.
    Thank you 😊

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +2

      They are on the list.

  • @rodrigo6459
    @rodrigo6459 4 ปีที่แล้ว +1

    This was a REALLY cool thing to watch... just like 2 weeks ago i was trying to add Dependency Inyection to my console app but i was looking forward to use native microsoft stuff.. Thanks for this!

  • @ManishaAgarwal
    @ManishaAgarwal 3 ปีที่แล้ว

    Hello Tim, i am new in .net core, i need your help in .net core in one of my poject, i want to check some users everyday for which i have created a .net core console app, so which service would be preferable hosted service or worker service. should be easily work on windows and linux both.

  • @blsilva89
    @blsilva89 4 ปีที่แล้ว

    Why do you use host class in console application? Is better? What is the advantage? I usually use an instance of ServiceCollection to configure DI and get the runner class. If anyone wants to explain to me I will be very thankful.
    Thanks for the video! Is very informative!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I use the Host class because it is the starting point for setting up the standard .NET Core features, not just DI. It connects to the configuration file(s) and it sets up logging as well.

  • @mylesdavies9476
    @mylesdavies9476 2 ปีที่แล้ว

    Sorry if I missed it but does the greeter service in this case then become the entry point for the application and where the main application code would be called from? I assume any further services would simply added to the container and the run method is only required on the 'entry' class?

  • @josepiratilla
    @josepiratilla 3 ปีที่แล้ว +1

    First of all excellent videos!. I wanted to add that at 38:00 another very good reason to pass parameters separately is to avoid the string manipulation if our log level is higher.

  • @thibaudgalland1524
    @thibaudgalland1524 4 ปีที่แล้ว +2

    Such a great video ! Just one question, why do you use ActivatorUtilities.CreateInstance(host.Services) instead of host.Services.GetRequiredService() ?

    • @sunilanthony17
      @sunilanthony17 4 ปีที่แล้ว

      He explains it because Interface doesn't have a constructor.

    • @thibaudgalland1524
      @thibaudgalland1524 4 ปีที่แล้ว +1

      @@sunilanthony17 with ActivatorUtilities.CreateInstance you can't as he explained. But with host.Services.GetRequiredService() you can (I'm using it all the time). That's why I would know why he use ActivatorUtilities, is there any advantage ? Speed ?

    • @sunilanthony17
      @sunilanthony17 4 ปีที่แล้ว

      @@thibaudgalland1524 Good to know, have you ever get this to work with Autofac.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Great question. In this example, it didn't matter. Either would have worked and the host.Services method would have been less messy. However, the way I did it will allow for more flexibility in the constructor call (you can pass in additional arguments, etc.) It would also allow us to not put the GreetingService in DI and yet still use DI for all subsequent calls. This probably deserves a topic all to itself.

    • @thibaudgallanddemanneville174
      @thibaudgallanddemanneville174 4 ปีที่แล้ว

      @@IAmTimCorey thank you for the answer! I'll keep this in mind for the future

  • @fevziozgul6780
    @fevziozgul6780 ปีที่แล้ว

    What is the purpose of using a transient scope in a console app? The way you use it in your demo, you only request it once. I suppose it is being used in Scoped mode in the end.

  • @Unsensational
    @Unsensational 4 ปีที่แล้ว +1

    Curious about your thoughts doing something like this versus using something like the worker template which has the dependency injection and uses a hosted service

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      A worker template is for long-running services. A console app is for doing a job and then quitting. They are different. It is just subtle.

  • @iandavies1524
    @iandavies1524 3 ปีที่แล้ว +1

    @26:47 not getting same results for mouse over - just 1st & last 2 lines. Latest VS19 installed. Any ideas anyone?

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว +1

      Interesting. Not sure why.

    • @wobblyrampack9655
      @wobblyrampack9655 3 ปีที่แล้ว

      I'm the same with latest VS19 installed - just 1st and last 2 lines. Strange!

    • @WillEhrendreich
      @WillEhrendreich 3 ปีที่แล้ว

      Same here, I would love the extra info!

    • @ashenlion805
      @ashenlion805 3 ปีที่แล้ว

      Anyone figure this out as I don't have the extra information either?

  • @noocyte
    @noocyte 4 ปีที่แล้ว +1

    Would like to see this for long running console apps, with safe shut down hook up.

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      You mean like a service or just for an application that takes a long time to run? I have a video on Worker Services.

  • @marierasmussen7799
    @marierasmussen7799 ปีที่แล้ว

    Please update. Great video but had to look elsewhere for tips/tricks for .net 6/7

  • @mauricioSolis-q5m
    @mauricioSolis-q5m ปีที่แล้ว

    Thank you Tim Really helpful video.
    I have the configuration part similar to you
    static void BuildConfig(IConfigurationBuilder builder)
    {
    var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
    builder.SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();
    }
    my current ASPNETCORE_ENVIRONMENT is Development...and it seems to override the values correctly with the Appsetting.Development.json from program.cs
    I initialized my service as you
    var host = Host.CreateDefaultBuilder()
    .ConfigureServices((context, services) =>
    {
    //Here you add services/Interfaces
    services.AddTransient();
    })
    .Build();
    var _handler = ActivatorUtilities.CreateInstance(DependencyInjectionConfiguration().Services);
    my handler is in a different file and the constructor is like this
    public Handler(IConfiguration configuration)
    {
    _configuration = configuration;
    }
    when I look at the configuration it does not show the provider for Development but for Production....
    Summarizing it seems like when I do the config it does the transform correctly but once I create the instance and I tried using the configuration is doing the transform from Production.
    do you know why this could be

    • @IAmTimCorey
      @IAmTimCorey  ปีที่แล้ว

      Console apps don't set the environment to Development by default. You would need to do that yourself. Since one isn't set, I believe the default value for that is Production.

  • @johnway6507
    @johnway6507 3 ปีที่แล้ว

    Great video... exactly what I'm looking for. I'm confused on a couple things. When I duplicate this code, the ActivatorUtilities.CreateInstance works even if you don't call services.addTransient(). Digging further, there are more services available in the "services" object within ConfigureServices than there are in the host.Services object. Even more confusing is that even when you add IGreetingService using AddTransient, it doesn't show up in the host.Services object. Can you help me understand what's going on?

  • @karwenzman
    @karwenzman ปีที่แล้ว

    Thanks for this nice video, Tim.
    Do you have a video that is explaining the usage of the configuration build process a bit more detailed (I am relating to content at minute 15+)? Or can you share me some links where this is explained? There are two questions in particular:
    1) addJsonFile(..., reloadOnChange = true)
    2) ASPNETCORE_ENVIRONMENT
    1) I can not figure out how to use this argument; who is getting the information, that the file has changed? what needs to be done to receive this information?
    2) If I want to code a plain console App, the ASPNETCORE_ENVIRONMENT is null(or an empty string???); how can I implement this?

    • @IAmTimCorey
      @IAmTimCorey  ปีที่แล้ว +1

      I don't believe I've gone that deep in a TH-cam video. This course covers it in more detail, including how to add the JSON file and how to work with the environment variables: www.iamtimcorey.com/courses/dotnet-core-appsettings-from-start-to-finish/

  • @ppcgnamda
    @ppcgnamda 4 ปีที่แล้ว +1

    Still not entirely sure what to do with this. Can you make an example video using this as a starting point?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I will add it to the list. Thanks for the suggestion.

  • @gbthakkar
    @gbthakkar 2 ปีที่แล้ว

    Serilog config is not connected to Host.CreateDefaultBuilder().
    I don't know if anybody was having this confusion.
    we create a IConfuguration (ConfigurationBuilder.Build) and pass it to Serilog configuration to use it.
    Then we create Host
    And say .UseSerilog (time 28::05 onward). Which may use the configuration provided earlier. But I so not see the connection between IConfiguration inside the host and the one which we created for the serilog.
    I am just trying setup something like below.
    var host = Host.CreateDefaultBuilder()
    .ConfigureHostConfiguration(o =>
    {
    o.SetBasePath(Directory.GetCurrentDirectory());
    o.AddJsonFile("appsetting.json");
    })
    .ConfigureAppConfiguration(o =>
    {
    o.SetBasePath(Directory.GetCurrentDirectory());
    o.AddJsonFile("appsetting.json");
    });
    Is it correct?

    • @IAmTimCorey
      @IAmTimCorey  2 ปีที่แล้ว

      The CreateDefaultBuilder method sets up the defaults for .NET Core (default logger, default configuration settings, etc.) We then extend that configuration when we add Serilog (replacing the default logger). As for your code, I don't think that looks right, but I can't say for certain. This video might help: th-cam.com/video/_2_qksdQKCE/w-d-xo.html

  •  3 ปีที่แล้ว

    What is the BuildConfig method for? Isn't CreateDefaultBuilder doing exactly that?
    Documentation for CreateDefaultBuilder:
    The following defaults are applied to the returned HostBuilder:
    - set the ContentRootPath to the result of GetCurrentDirectory()
    - load host IConfiguration from "DOTNET_" prefixed environment variables
    - load app IConfiguration from 'appsettings.json' and 'appsettings.[EnvironmentName].json'

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว

      We call BuildConfig and set that up manually because we want different settings than the defaults. If you want to make modifications to how things are set up, you need to override the defaults like we are doing.

  • @ardavaztterterian1211
    @ardavaztterterian1211 4 ปีที่แล้ว +1

    Could you please do a video on implementing SignalR and connecting hubs in .NET Core? Thank you as always!

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I will add it to the list. Thanks for the suggestion.

  • @waynehawkins654
    @waynehawkins654 ปีที่แล้ว

    Hello Tim - It would be good to have something like this but using EF 7 as well to update DTOs to DB (AutoMapper), that is Add, Update, Delete. But don't use APIs with EF to do the changes, a raw updated within it's own class. I can get things working but many road blocks when it comes to tracking and doing updates.

  • @billtjohnson6747
    @billtjohnson6747 3 ปีที่แล้ว

    When discussing how much MS help/docs have improved ... your video shows a lot more help in the tooltip than I get when hovering over the "Host.CreateDefaultBuilder" method. I have the latest VS 2019. However, I see a much smaller description of the method. Is that an option? - I can't find any setting for a more verbose help message than I see.

  • @hiteshprajapati4266
    @hiteshprajapati4266 3 ปีที่แล้ว

    Please make a vedio on ios push notification stuff using. Net core and bit description about. Net framework about ios push notifications

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว +1

      I will add it to the list. Thanks for the suggestion.

  • @-martintheengineer-7465
    @-martintheengineer-7465 4 ปีที่แล้ว +1

    For me it would be interesting in using WPF for this technique and to define a singleton class with this techinique. May be copy the code from the console to WPF? Best regards Martin

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +3

      I can add WPF to the suggestion list. It would be a bit different for WPF because you need to register your forms, and if you use MVVM that would be even more different but it can be done.

    • @erikthysell
      @erikthysell 4 ปีที่แล้ว

      @@IAmTimCorey wpf + mvvm + .net 5 : yeees please :)

  • @kunik5935
    @kunik5935 4 ปีที่แล้ว +1

    Hi Tim. First, I wanted to thank you for this video. It is always easier to understand something when you do it from the beginning (with console app). I have a question about those appSettings files. I've made this application just like you in this video. I've added the ASPNETCORE_ENVIRONMENT variable in environment variables (I've added 'Development') but the appsettings.Development.json file doesn't overwrite the regular appsettings.json file. Could you shortly explain if I have to do something with this to work?
    PS: I checked, and the application correctly reads this variable and the file name is correct

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      I have a video on appsettings.json on the schedule for very soon to go over this in more depth. It can depend on the order the files are registered in (should be fine if you let it register automatically). There may also be a typo (I know you checked). The file also might not be marked to copy to the output directory. The environment variable might not be being read for some reason.

    • @kunik5935
      @kunik5935 4 ปีที่แล้ว

      @@IAmTimCorey ok. I will check one more time. I will wait for that video 😉

    • @jaytmunn
      @jaytmunn 3 ปีที่แล้ว

      @@kunik5935 Not sure if you're still looking for this, but I had the same issue. I ended up modifying the Host.CreateDefaultBuilder to add a chained configuration call:
      .ConfigureAppConfiguration((config) =>
      config.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true, reloadOnChange: true))

  • @donadickens6127
    @donadickens6127 ปีที่แล้ว

    When do you add context? What does it mean? (Context, config)=> {}

  • @shaiarocks
    @shaiarocks 3 ปีที่แล้ว

    I use VS 2019 Enterprise Edition. I like how you typed in "IConfigrationBuilder" and VS added the using statement. My version of VS does not do that. I know how to add the using statement, I would really like having automatically done for me. Is there something special you have done to make that work? Is there an setting in options? Having using statements add automatically would be a great time saver!

  • @michaelraab2574
    @michaelraab2574 3 ปีที่แล้ว

    ILogger : Error ILogger is not generic (latest version of serilog)

  • @TaginusOfAinusgard
    @TaginusOfAinusgard 4 ปีที่แล้ว +1

    I actually figured this out on my own when playing one day. However, there are tons of other things I learned in this video that I wasn't aware of. Subscribed!

  • @Strateg2300
    @Strateg2300 2 ปีที่แล้ว +1

    Это великолепно, спасибо большое! => It's great, thank you very much!

  • @messenja2547
    @messenja2547 ปีที่แล้ว

    Hi Tim, have you similar video for net core 6/7? Cant find any

  • @zxcvb_bvcxz
    @zxcvb_bvcxz 4 ปีที่แล้ว

    What if you have an existing app you want to convert to using DI. Especially using AutoFac. Where would you start, how would you choose how to split up the application?

  • @Jason_Shave
    @Jason_Shave 4 ปีที่แล้ว

    Great video. One 'add-on' you could do to this video is to cover storage/retrieval of secrets. This is sometimes a challenge in a console application but can be done if you extend your example to include something like this: (i.e. github.com/jasonshave/ConsoleSecrets). I don't want my secrets 'leaking' into my repository and showing people this very common tactic would be very valuable.

  • @martineberle4956
    @martineberle4956 2 ปีที่แล้ว

    Hello and thank you for your great tutorial, I was able to use it successfully. Can you possibly still tell me how I get the logs from Serilog in a file?
    Many greetings from Lake Constance (Germany)

    • @martineberle4956
      @martineberle4956 2 ปีที่แล้ว

      This is my solution for now. I have added it to the logger configuration
      .WriteTo.File(@"log\log.txt", rollingInterval: RollingInterval.Day)

  • @DrCox-xx8tu
    @DrCox-xx8tu 4 ปีที่แล้ว

    Sorry for this stupid question, but I'm new to the C# family (Java coder here) and I wonder why you not installed the NuGet Package "Serilog" as a whole?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว

      I just installed the pieces that I needed. I believe the piece I used installed the main package behind the scenes. We don't install everything Serilog offers because we only need specific things from it. It is like going to the store and getting just the parts we need for a project rather than buying the whole store.

  • @Lhorez
    @Lhorez 4 ปีที่แล้ว

    I'm working on a dotnet core console app and just happened on this video a couple of days ago. The implementation is nice and clean but I'm a little lost at one part. I have code very similar to yours (gist.github.com/Maleki/63f3c8186d1c903ef545cbc5bd58f525) but I can comment out the AddTransient and the code still works just fine. Does the instance need to be defined in DI? Or is it just the dependencies?

    • @IAmTimCorey
      @IAmTimCorey  4 ปีที่แล้ว +1

      Since we are calling it using the activator, we don't need to put it in to the DI system, but if we wanted to get that class anywhere else, we would need it in DI so I added it for completion.

  • @saadbinsami4801
    @saadbinsami4801 3 ปีที่แล้ว

    at 29.49 i get a local parameter services can not be declared in this scope.

  • @fifty6737
    @fifty6737 2 ปีที่แล้ว

    In terms of Dependency Injection, i've been using the microsoft one with ASP.NET 6, i've never needed to use something like Autofac, what does Autofac provide that the microsoft one doesn't have?

    • @IAmTimCorey
      @IAmTimCorey  2 ปีที่แล้ว +1

      More granular options for your dependencies among other things. If you don't need it, don't use it.

  • @panagiotisveranoudis3025
    @panagiotisveranoudis3025 3 ปีที่แล้ว +2

    Great stuff, appreciate the time and effort you put into this. Really high quality material.

    • @IAmTimCorey
      @IAmTimCorey  3 ปีที่แล้ว

      Glad you enjoyed it!