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

Поделиться
HTML-код
  • Опубликовано: 17 июн 2024
  • .NET Core has brought a lot of great benefits right into the .NET language. We get dependency injection, a much better configuration system, and we get a common logging system that is easy to use. The only problem is that mainly, we only get these things set up for us in web environments. What happens when we want to get these things running in a Console app? Well, it takes a bit of extra work, but it can be done. In this video, we are going to set up dependency injection, configuration using appsettings.json, and logging using Serilog in a Console application.
    Source Code: leadmagnets.app/?Resource=Bet...
    Mailing List: signup.iamtimcorey.com/
    Purchase Courses: iamtimcorey.com
    0:00 - Intro
    1:49 - Creating Console App (.NET Core)
    3:35 - NuGet references
    7:29 - Editing csproj file in .NET Core
    9:15 - Add application settings json file
    10:46 - Define goals
    11:30 - Builder setup: BuildConfig
    21:12 - Serilog setup: LoggerConfiguration
    25:04 - Host setup: CreateDefaultBuilder
    30:11 - Program entry point Class
    39:51 - Dependency Injection
    43:04 - Calling entry point in Main()
    45:21 - Configuration for Serilog in appsetings.json
    50:10 - Runnning the application and fixing exceptions
    55:02 - Recap, summary and concluding remarks
    Thanks to Ralfs HBK for the chapter breakdown

Комментарии • 693

  •  3 года назад +233

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

    • @MarioMaletic
      @MarioMaletic 3 года назад

      lol

    • @YoloMonstaaa
      @YoloMonstaaa 3 года назад +1

      Truuue

    • @lborate3543
      @lborate3543 3 года назад

      Lol so true.

    • @ibrahimhussain3248
      @ibrahimhussain3248 3 года назад +16

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

    • @ericjalbert9433
      @ericjalbert9433 3 года назад +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

  • @TheJessejunior
    @TheJessejunior 3 года назад +16

    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  3 года назад +3

      I am glad my content has been so helpful.

  • @myemailvl
    @myemailvl 3 года назад +2

    Thanks, Tim. I think your videos is the most useful upon all other programming tutorials on RUclips. Especially for people with some experience as a programmer.

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +1

      Great to hear! It is good to know that the training is valuable to folks with your level of experience.

  • @KhachaturStepanyan
    @KhachaturStepanyan 3 года назад

    So well put, I almost never come across a video where you follow tutorial step by step and it works, usually something is missing, something is forgotten
    thank you!

  • @divanvanzyl7545
    @divanvanzyl7545 3 года назад +3

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

  • @JoshuaKersey
    @JoshuaKersey Год назад

    This one had a lot of great information in it. Thanks Tim! Keep them coming!

  • @oncalldev
    @oncalldev 3 года назад +5

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

  • @TaginusOfAinusgard
    @TaginusOfAinusgard 3 года назад +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!

  • @JonathanPeel
    @JonathanPeel 3 года назад +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  3 года назад +1

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

  • @mohammedal-mudhafar4602
    @mohammedal-mudhafar4602 5 месяцев назад

    Your content's trustworthiness has become my go-to, when looking for C#/.Net subjects.

  • @sathyajithkalyadan2971
    @sathyajithkalyadan2971 2 года назад

    Thanks Tim, you are a great teacher. The way you explain things makes it much much easier to understand and adapt.

  • @ibrahimhussain3248
    @ibrahimhussain3248 3 года назад +48

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

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +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!

  • @panagiotisveranoudis3025
    @panagiotisveranoudis3025 3 года назад +2

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

  • @AmitDileepKulkarni
    @AmitDileepKulkarni 3 месяца назад

    Thanks Tim for teaching us dependency injection in a very simple way !

  • @88spaces
    @88spaces Год назад

    Thanks, Tim. This video helped me a lot. I liked the underscore tip. I've been wanting to figure that out for a while. And using Serilog looks very promising.

  • @wobblyrampack9655
    @wobblyrampack9655 3 года назад

    Wonderful! Thanks so much Tim. Trying to get up to speed quickly with C# and I learnt so much from this video.

  • @heradsinn
    @heradsinn 3 года назад

    As always, extremely useful! I recommend this channel whenever I can to my colleagues and friends!

  • @TheHosuwisp
    @TheHosuwisp 3 года назад

    This video is just the epic way to understand complicated things. Well done.

  • @jexter7200
    @jexter7200 2 года назад

    Great video, thank you for taking the time to explain a few of the 'simple' things. If you don't know a few of them good enough, they are not simple

  • @rodrigo6459
    @rodrigo6459 3 года назад +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!

  • @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!!!

  • @MichaelMoore-zi2yf
    @MichaelMoore-zi2yf 3 года назад

    You have a great and simple way of explaining things. Very clear.

  • @pauldechampignon2287
    @pauldechampignon2287 3 года назад

    Cheers Tim. That is what I was looking for! Great film.

  • @mbrotto1970
    @mbrotto1970 Год назад

    I love the refactoring option (underscore) update...I have been using that for a while now...just popped back as I had lost it...oh and the content is great too ;o) Thanks for the great content Tim.

  • @kopilkaiser8991
    @kopilkaiser8991 11 месяцев назад

    I was looking for a video like this. Thanks to you. I was able to understand and achieve this.

  • @BlahzayBeta
    @BlahzayBeta 4 дня назад

    The copy output directory tip was clutch! Exactly the issue I was having. Great video as always. Thanks

  • @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.

  • @maheshshinde4168
    @maheshshinde4168 2 года назад

    Thank you Tim! It is helping me understand this concept in detail.

  • @DCombsify
    @DCombsify 9 месяцев назад

    Thank you, Tim. This is exactly what i have spent the last day trying to understand. I should have looked at your video hours ago. lol

    • @IAmTimCorey
      @IAmTimCorey  9 месяцев назад

      I am glad it was helpful.

  • @oriwiesel5363
    @oriwiesel5363 3 года назад

    I so happy that you and I are living on the same time!
    Thank you!

  • @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.

  • @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 :)

  • @Benexdrake
    @Benexdrake Год назад

    Thank u for this Video, learning EF Core and DI in Blazor, but seeing this in Console is awsome.

  • @migueljara8692
    @migueljara8692 9 месяцев назад

    Thanks for sharing this, Tim., very well explained!

  • @arthinkers
    @arthinkers Год назад

    Very well laid out Tim. Thank you so much and you are right, Serilog is a good tool and with your code right here, anyone can be up and running in a few minutes.

  • @ghostfreak1902
    @ghostfreak1902 2 года назад

    This was a magnificent video and helped me a lot.
    Thanks for your hard work and your awesome channel. Keep up the good work and thanks a lot :D

  • @hamidrezaashkiyan
    @hamidrezaashkiyan 3 года назад +1

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

    • @IAmTimCorey
      @IAmTimCorey  3 года назад

      Hope you enjoyed it!

    • @fernandopelacini5662
      @fernandopelacini5662 3 года назад

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

  • @jerrydsta1056
    @jerrydsta1056 2 года назад

    This is a fantastic videos that shows how to do dependency injections, logging etc. Highly recommended to all.

  • @pietsmitsa
    @pietsmitsa 2 года назад

    Hi Tim, this was awesome as always. Thank you!

  • @mohamadkibaly808
    @mohamadkibaly808 Год назад

    That's a great start for Console applications
    Thanks Tim 👍

  • @garimasingh6341
    @garimasingh6341 Год назад

    You are brilliant , you have explained and cleared my doubts in such a beautiful manner

  • @parko1965
    @parko1965 Год назад

    Tutorials like these are little gems from this man.

  • @seijumimurasakibara5516
    @seijumimurasakibara5516 Год назад

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

  • @sunilanthony17
    @sunilanthony17 3 года назад +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  3 года назад +1

      You are welcome.

    • @iambhanu7
      @iambhanu7 3 года назад +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 3 года назад +1

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

  • @devongribbin9620
    @devongribbin9620 3 года назад

    Really great video Tim. Thank you.

  • @georgesaeid7231
    @georgesaeid7231 2 года назад

    This was so wonderful, thank you Tim.

  • @Die_MF_Die
    @Die_MF_Die 2 года назад

    Awesome lesson, Tim! its very useful for me. Thanks!

  • @ssushovan
    @ssushovan Год назад

    This is an excellent tutorial. Thanks, Tim!😊

  • @juanmanuelgordillogonzalez7186
    @juanmanuelgordillogonzalez7186 3 года назад

    Cool boiler plate Tim, thank you!

  • @immino
    @immino 3 года назад

    Wonderful content, thank you Tim.

  • @sarracenogamer7375
    @sarracenogamer7375 2 года назад

    I love your tutorials step by step, thank you for share your knowlage :)

  • @krsharodh
    @krsharodh 2 года назад

    Brilliant! It helped me with a coding assignment for a job.

  • @chillimanfly2859
    @chillimanfly2859 3 года назад

    Amazing as always, thanks Tim

  • @guillermovillalta6322
    @guillermovillalta6322 3 года назад

    This was AMAZING! Thanks Tim!!

  • @aprivi
    @aprivi Месяц назад

    As always, very good content!!!

  • @bendunaway8296
    @bendunaway8296 3 года назад

    Dude, what a great video. I'm going to check out your site.

    • @IAmTimCorey
      @IAmTimCorey  3 года назад

      Please do! IAmTimCorey.com and RUclips channel ruclips.net/channel/UC-ptWR16ITQyYOglXyQmpzw Purchases directly fund my ability to provide the free content. Thank you for being a big part of making these free videos available.

  • @jalvrus
    @jalvrus 3 года назад +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  3 года назад

      Great tip! Thanks for sharing

  • @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.

  • @davidos533
    @davidos533 2 года назад

    Thank you! Very much, very good consideration, finally i understand DI.

  • @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.

  • @serjnell4089
    @serjnell4089 2 года назад

    Best explanations on subject as always!

  • @TonTruong
    @TonTruong 3 года назад

    wow, this is exactly what i looking for in the morning

  • @bobcynical2316
    @bobcynical2316 Год назад

    INCREDIBLE. AMAZING. LIFE-CHANGING.
    THANK YOU TIM.
    YOU HAVE SAVED MY LIFE.
    🙃

    • @IAmTimCorey
      @IAmTimCorey  Год назад

      I'm glad it was helpful.

    • @bobcynical2316
      @bobcynical2316 Год назад

      @@IAmTimCorey THE MESSIAH HAS REPLIED. WHAT IS EXISTENCE.

  • @marceloleoncaceres6826
    @marceloleoncaceres6826 7 месяцев назад

    Another great video, thanks a lot for sharing your knowledge and time,

  • @sergio.diachenko
    @sergio.diachenko 3 года назад

    Tim, thank you so much, this is so usefull. Additional thanks for some tips and tricks.

  • @eleonoravasylenko7094
    @eleonoravasylenko7094 2 года назад

    Great lesson, good examples, thanks a lot!

  • @medusaskull9625
    @medusaskull9625 2 года назад

    Excellent explanation as always

  • @edelbertoreyes3663
    @edelbertoreyes3663 3 месяца назад

    Thank you for sharing. It is very interesting and useful.

  • @shuaibahamed8692
    @shuaibahamed8692 2 года назад

    Dude I have learned so much from this channel

  • @vnuuk
    @vnuuk 2 года назад

    This video helped - thank you!

  • @otmanm4095
    @otmanm4095 3 года назад

    Thank you very much, you make very great content!

  • @lockegarmin4615
    @lockegarmin4615 3 года назад +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  3 года назад +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.

  • @pez5491
    @pez5491 3 года назад

    Excellent! I wasn't doing anything for such toutorial :D

  • @danielweaver6110
    @danielweaver6110 3 года назад +6

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

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +1

      Thanks for your vote.

    • @tinoh.4573
      @tinoh.4573 3 года назад

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

  • @RalfsBalodis
    @RalfsBalodis 3 года назад

    This.will.be.hard.to.chew.
    Thanks for the explanations!

  • @yourittrainer3196
    @yourittrainer3196 Год назад

    Awesome video Time. Thank you so much

  • @scottridings6008
    @scottridings6008 3 года назад

    Best explainer on the internet!

  • @nguyenphu3552
    @nguyenphu3552 2 года назад

    Thanks, it's very useful ^^

  • @Otonium
    @Otonium 3 года назад

    So enjoyable and clear.

  • @jojyvarghese174
    @jojyvarghese174 3 года назад

    Very nice and useful tutorial

  • @MrKaviraj75
    @MrKaviraj75 3 года назад +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  3 года назад +1

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

  • @user-pt7lu7cd7c
    @user-pt7lu7cd7c 3 года назад

    I think I need to subscribe.
    Thanks for the lesson.

  • @shashankkhandelwal3514
    @shashankkhandelwal3514 3 года назад +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 😊

  • @user-yv2tb1rq2h
    @user-yv2tb1rq2h 2 года назад +1

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

  • @teijeterbals1203
    @teijeterbals1203 3 года назад +3

    Wow. That UnderScore tweak from 33:57 is brilliant! Never knew this, and never understood why this isn't the default

  • @MrFEMGM
    @MrFEMGM Год назад

    Excellent video.

  • @schh486
    @schh486 3 года назад +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  3 года назад +1

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

  • @rigel_riggs
    @rigel_riggs 3 года назад

    I really love your videos. My only contention (and this is just the unfortunate reality for myself) is that I don't have access to Nuget packages at my workplace, whatsoever. I still learn plenty though.

    • @IAmTimCorey
      @IAmTimCorey  3 года назад +1

      That's rather unfortunate and something that I would recommend you talk to management about (you probably have already but tell them Tim says they should change their stance). NuGet provides you with pre-built pieces of code that allows you to not reinvent the wheel each time. Further, .NET Core itself relies on NuGet packages to add to it. Instead of making one bloated system, Microsoft created NuGet packages so that we can add just the things we need.

  • @rociomejia7356
    @rociomejia7356 3 месяца назад

    Tim I cannot give so many thumbs for all times I see this video. :)

  • @ricardogriffith9384
    @ricardogriffith9384 2 года назад

    Awesome video!

  • @PaulSmithGainesville
    @PaulSmithGainesville Год назад

    Thanks Tim!

  • @AlbertoMonteiro
    @AlbertoMonteiro 3 года назад

    Awesome, you have a very nice didactic

  • @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 - ruclips.net/user/IAmTimCoreysearch?query=test

  • @weifengmao
    @weifengmao 3 года назад

    Interesting approach I usually use service providers in combination with service collection to achieve Di outside aspnetcore

  • @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?

  • @Dotnetexplorer
    @Dotnetexplorer 2 года назад

    Great Content

  • @theoceandragongaming
    @theoceandragongaming 2 года назад

    Excellent!!

  • @kolesplace
    @kolesplace 3 года назад

    Fantastic... thanks

  • @mrsajjad30
    @mrsajjad30 2 года назад

    Thank you for a great video. Please make a tutorial on how do we set up these services in a WFP application?

  • @Azcane
    @Azcane 3 года назад +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.