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

Sdílet
Vložit
  • čas přidán 19. 06. 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

Komentáře • 693

  •  Před 3 lety +234

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

    • @MarioMaletic
      @MarioMaletic Před 3 lety

      lol

    • @YoloMonstaaa
      @YoloMonstaaa Před 3 lety +1

      Truuue

    • @lborate3543
      @lborate3543 Před 3 lety

      Lol so true.

    • @ibrahimhussain3248
      @ibrahimhussain3248 Před 3 lety +16

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

    • @ericjalbert9433
      @ericjalbert9433 Před 3 lety +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 Před 3 lety +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  Před 3 lety +3

      I am glad my content has been so helpful.

  • @KhachaturStepanyan
    @KhachaturStepanyan Před 3 lety

    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!

  • @TaginusOfAinusgard
    @TaginusOfAinusgard Před 3 lety +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!

  • @mohammedal-mudhafar4602
    @mohammedal-mudhafar4602 Před 5 měsíci

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

  • @myemailvl
    @myemailvl Před 3 lety +2

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

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +1

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

  • @divanvanzyl7545
    @divanvanzyl7545 Před 3 lety +3

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

  • @ibrahimhussain3248
    @ibrahimhussain3248 Před 3 lety +48

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

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +12

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

    • @Kevin-mb4xf
      @Kevin-mb4xf Před 3 lety

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

  • @oncalldev
    @oncalldev Před 3 lety +5

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

  • @JoshuaKersey
    @JoshuaKersey Před rokem

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

  • @88spaces
    @88spaces Před rokem

    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.

  • @rodrigo6459
    @rodrigo6459 Před 3 lety +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!

  • @JonathanPeel
    @JonathanPeel Před 3 lety +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  Před 3 lety +1

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

  • @AmitDileepKulkarni
    @AmitDileepKulkarni Před 3 měsíci

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

  • @goodoleme747
    @goodoleme747 Před 3 lety +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.

  • @oscarjr2088
    @oscarjr2088 Před 3 lety +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!!!

  • @sathyajithkalyadan2971

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

  • @josepiratilla
    @josepiratilla Před 3 lety +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.

  • @panagiotisveranoudis3025
    @panagiotisveranoudis3025 Před 3 lety +2

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

  • @wobblyrampack9655
    @wobblyrampack9655 Před 3 lety

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

  • @heradsinn
    @heradsinn Před 3 lety

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

  • @jexter7200
    @jexter7200 Před 2 lety

    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

  • @TheHosuwisp
    @TheHosuwisp Před 3 lety

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

  • @mbrotto1970
    @mbrotto1970 Před rokem

    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.

  • @lambda-snail
    @lambda-snail Před 3 lety

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

  • @BlahzayBeta
    @BlahzayBeta Před 6 dny

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

  • @MichaelMoore-zi2yf
    @MichaelMoore-zi2yf Před 3 lety

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

  • @arthinkers
    @arthinkers Před rokem

    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.

  • @oriwiesel5363
    @oriwiesel5363 Před 3 lety

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

  • @kopilkaiser8991
    @kopilkaiser8991 Před 11 měsíci

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

  • @Benexdrake
    @Benexdrake Před rokem

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

  • @pauldechampignon2287
    @pauldechampignon2287 Před 3 lety

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

  • @maheshshinde4168
    @maheshshinde4168 Před 2 lety

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

  • @DCombsify
    @DCombsify Před 9 měsíci

    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

  • @hamidrezaashkiyan
    @hamidrezaashkiyan Před 3 lety +1

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

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety

      Hope you enjoyed it!

    • @fernandopelacini5662
      @fernandopelacini5662 Před 3 lety

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

  • @mohamadkibaly808
    @mohamadkibaly808 Před rokem

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

  • @conaxlearn8566
    @conaxlearn8566 Před 3 lety +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  Před 3 lety +1

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

  • @migueljara8692
    @migueljara8692 Před 9 měsíci

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

  • @jerrydsta1056
    @jerrydsta1056 Před 2 lety

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

  • @jalvrus
    @jalvrus Před 3 lety +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.

  • @sunilanthony17
    @sunilanthony17 Před 3 lety +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  Před 3 lety +1

      You are welcome.

    • @iambhanu7
      @iambhanu7 Před 3 lety +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 Před 3 lety +1

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

  • @garimasingh6341
    @garimasingh6341 Před rokem

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

  • @parko1965
    @parko1965 Před rokem

    Tutorials like these are little gems from this man.

  • @juanmanuelgordillogonzalez7186

    Cool boiler plate Tim, thank you!

  • @georgesaeid7231
    @georgesaeid7231 Před 2 lety

    This was so wonderful, thank you Tim.

  • @ssushovan
    @ssushovan Před rokem

    This is an excellent tutorial. Thanks, Tim!😊

  • @krsharodh
    @krsharodh Před 2 lety

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

  • @lockegarmin4615
    @lockegarmin4615 Před 3 lety +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  Před 3 lety +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.

  • @pietsmitsa
    @pietsmitsa Před 2 lety

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

  • @immino
    @immino Před 3 lety

    Wonderful content, thank you Tim.

  • @RobertOspara
    @RobertOspara Před 2 lety +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.

  • @Die_MF_Die
    @Die_MF_Die Před 2 lety

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

  • @devongribbin9620
    @devongribbin9620 Před 3 lety

    Really great video Tim. Thank you.

  • @sarracenogamer7375
    @sarracenogamer7375 Před 2 lety

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

  • @ghostfreak1902
    @ghostfreak1902 Před 2 lety

    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

  • @bendunaway8296
    @bendunaway8296 Před 3 lety

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

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety

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

  • @seijumimurasakibara5516

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

  • @davidos533
    @davidos533 Před 2 lety

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

  • @chillimanfly2859
    @chillimanfly2859 Před 3 lety

    Amazing as always, thanks Tim

  • @guillermovillalta6322
    @guillermovillalta6322 Před 3 lety

    This was AMAZING! Thanks Tim!!

  • @serjnell4089
    @serjnell4089 Před 3 lety

    Best explanations on subject as always!

  • @aprivi
    @aprivi Před měsícem

    As always, very good content!!!

  • @eleonoravasylenko7094
    @eleonoravasylenko7094 Před 2 lety

    Great lesson, good examples, thanks a lot!

  • @edelbertoreyes3663
    @edelbertoreyes3663 Před 4 měsíci

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

  • @sergio.diachenko
    @sergio.diachenko Před 3 lety

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

  • @bobcynical2316
    @bobcynical2316 Před rokem

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

  • @RalfsBalodis
    @RalfsBalodis Před 3 lety

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

  • @TonTruong
    @TonTruong Před 3 lety

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

  • @danielweaver6110
    @danielweaver6110 Před 3 lety +6

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

    • @IAmTimCorey
      @IAmTimCorey  Před 3 lety +1

      Thanks for your vote.

    • @tinoh.4573
      @tinoh.4573 Před 3 lety

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

  • @vnuuk
    @vnuuk Před 2 lety

    This video helped - thank you!

  • @marceloleoncaceres6826
    @marceloleoncaceres6826 Před 7 měsíci

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

  • @pez5491
    @pez5491 Před 3 lety

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

  • @otmanm4095
    @otmanm4095 Před 3 lety

    Thank you very much, you make very great content!

  • @shuaibahamed8692
    @shuaibahamed8692 Před 2 lety

    Dude I have learned so much from this channel

  • @schh486
    @schh486 Před 3 lety +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  Před 3 lety +1

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

  • @medusaskull9625
    @medusaskull9625 Před 2 lety

    Excellent explanation as always

  • @MrKaviraj75
    @MrKaviraj75 Před 3 lety +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  Před 3 lety +1

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

  • @shashankkhandelwal3514
    @shashankkhandelwal3514 Před 3 lety +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 😊

  • @simoncampbell-smith6745
    @simoncampbell-smith6745 Před 3 lety +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?

  • @Tolg
    @Tolg Před 3 lety +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 Před 3 lety

      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 - czcams.com/users/IAmTimCoreysearch?query=test

  • @Otonium
    @Otonium Před 3 lety

    So enjoyable and clear.

  • @yourittrainer3196
    @yourittrainer3196 Před rokem

    Awesome video Time. Thank you so much

  • @rigel_riggs
    @rigel_riggs Před 3 lety

    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  Před 3 lety +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.

  • @scottridings6008
    @scottridings6008 Před 3 lety

    Best explainer on the internet!

  • @weifengmao
    @weifengmao Před 3 lety

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

  • @jojyvarghese174
    @jojyvarghese174 Před 3 lety

    Very nice and useful tutorial

  • @teijeterbals1203
    @teijeterbals1203 Před 3 lety +3

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

  • @nguyenphu3552
    @nguyenphu3552 Před 2 lety

    Thanks, it's very useful ^^

  • @user-pt7lu7cd7c
    @user-pt7lu7cd7c Před 3 lety

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

  • @AlbertoMonteiro
    @AlbertoMonteiro Před 3 lety

    Awesome, you have a very nice didactic

  • @Azcane
    @Azcane Před 3 lety +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.

  • @PaulSmithGainesville
    @PaulSmithGainesville Před rokem

    Thanks Tim!

  • @nacertabib3158
    @nacertabib3158 Před 3 lety

    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  Před 3 lety +1

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

  • @MrFEMGM
    @MrFEMGM Před 2 lety

    Excellent video.

  • @TwitchingShark
    @TwitchingShark Před 3 lety

    you can replace the interface with 'typeof(FooClass)' if you like to extend classes instead.
    I'm not a fan of interfaces myself. I like strict types :)

  • @ricardogriffith9384
    @ricardogriffith9384 Před 2 lety

    Awesome video!

  • @mrsajjad30
    @mrsajjad30 Před 2 lety

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

  • @Imafriggingoddess
    @Imafriggingoddess Před 3 lety

    Great video as always! How would one setup dependency injection in a class library project? The context is a blazorserver app using a repository pattern where the repository/services is in its own project being called from the blazor components.

  • @lesptitsoiseaux
    @lesptitsoiseaux Před rokem

    Hi Tim, working for a SAAS startup as an API & Integrations PM, I can code to a certain degree. What I would love to learn more best practices on is an modern .Net6+ C# console app that queries external REST API's to consume JSON, work it and post/put some things back while storing others on the local file system. All on a task scheduler basis. I am working on this on my spare time, and I think in this middleware world we are reinventing, what I'm talking about is commonly searched for even though its not Maui sexy and may be worth evaluating for a really wonderful video?🤩

  • @Mimmsanfrostborned
    @Mimmsanfrostborned Před 2 lety +1

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