Factory Pattern in C# with Dependency Injection

Поделиться
HTML-код
  • Опубликовано: 22 ноя 2024

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

  • @88spaces
    @88spaces 2 года назад +60

    I like that you include your mistakes in your videos because it happens all the time with everyone. It demonstrates that code is not magic and you have to know the rules.

  • @88spaces
    @88spaces 2 года назад +9

    What is an abstract factory is a frequently asked interview question. This video makes it clear what it is and is very helpful. Thanks for making it.

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

    ❤ From India. No matter how much knowledge a person have teaching someone is an Art. Appreciate your effort.

  • @TheJessejunior
    @TheJessejunior 2 года назад +19

    there are some concepts that I read a lot and about and still have dificult to grasp the intent... But it always gets very clear when you talk about it. Thanks for all theese years of valuable help!

  • @kdcurrin
    @kdcurrin 2 года назад +7

    Thanks, Tim your approach of trying to break these complex topics down into easy-to-understand examples is really helpful. I have recently started a new job as a developer and your free and paid courses are 100% why I can take this opportunity. Just wanted to say thank you!

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +4

      You are welcome. Congratulations on the new job!

  • @mikemcgrumpy
    @mikemcgrumpy 2 года назад +10

    Hi Tim. Just wanted to say thanks. I spent ages reading blog posts and googling on how to create a DI factory. This video is the only content I found that actually told me how to do it in a simple, practical way and with minimal code (specifically, your vehicle example was what saved my butt.) Appreciated!

  • @sammynochains3455
    @sammynochains3455 2 года назад +1

    Can i just say .. this is God's work. Where so many people focus on java and open end env's, you are a gem in the rough .. thanks Tim ..

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

    Thanks for another great video! I started to write my own factory class and then saw this video. Your method is so much more efficient and reusable than what I had planned. Using generics and an extension method is just brilliant. I love it! I really appreciate what you do for the developer community.

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

      I am glad it was so helpful.

  • @irlonterblanche1639
    @irlonterblanche1639 2 года назад +1

    Wow, I'm only 13 minutes into this video, and already you have clarified so much! Thank you for making a difference!

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

    i was trying to write a factory with dependency injection, this helped me. thank you

  • @runtimmytimer
    @runtimmytimer 2 года назад +1

    Great vid. One of those "lightbulb" techniques when you see you think "brilliant." A much cleaner implementation than I've used in the past. You're definitely right, Tim, this is a niche use case but a very elegant implementation to solve the problem.

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

    Your abstract factory is truly an elegant bit of code. Thanks for posting!

  • @d3tn3tracer
    @d3tn3tracer 2 года назад +1

    Thanks Tim. Your videos, education, and entusiasm to help others is so good! Thx a lot Tim.

  • @JoeBonez
    @JoeBonez 2 года назад +1

    I have never considered this use of Func before. Very good info, thanks.

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

      You are welcome.

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

      You are not alone -- I think the idea of using/passing/injecting a delegate is usually not most people's first thought. Even the idea of passing a method as a parameter, doesn't seem to come naturally. But with time/experience and presence of thought as you code, it's another tool that works in your favor!

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

    It would never have dawned on me that one can put a method in a service container, because that's what a Func is, right? (at 11:20) I had to go back to reviewing delegates and factory patterns. and then I got back to this video. And this kind of makes sense now. The requesting in the subclass of @inject Func. that moment. nice. something clicked.

  • @neopro688
    @neopro688 2 года назад +1

    very good video, open my mind when you show funcs in injection dependency injection.

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

    I actually had to use a factory two days ago for ef core db context. My app is a WPF and since using a db context gives u a singleton no matter if u declare it a transient. So I used the built in factory to resolve the issue I was havin with efcore auto tracking.

  • @viniciustrindade6675
    @viniciustrindade6675 Год назад +2

    Tim, please make videos about the other design patterns!!! love from brazil

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

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

  • @williameduardo7020
    @williameduardo7020 2 года назад +1

    Great video Tim. I have seen this for multitenant where we needed to connect to a database to get the user's connection string to another database.

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

    Hey! Nice video! But I wonder if injecting the IServiceProvider interface into AbstractFactory would be bad approach. Then, in the AbstractFactory.Create method instead of calling Func just use GetRequiredService. That way we can avoid creating singletons of Func.

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

      That gets into the Service Locator anti-pattern, where we aren't declaring our dependencies up front. You could do it, but this is structurally a better way of using the DI system so that you declare your dependencies up front.

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

      @@IAmTimCorey Ahh. So much to learn! Thank you for your time and answer ☺️

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

    Hey Tim, the timing of this video was perfect for the project I'm currently working on. It's been a challenge trying to Unit Test until now. This pattern is like finding that last piece of the puzzle, lying next to a dust bunny under the couch, to complete the blue sky. Thank you @iamtimcorey , I am a very happy camper! 😊

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

      I am glad it was so helpful.

  • @err_0-5rZ
    @err_0-5rZ 2 года назад

    Here we go again right after just finishing the DRY, SOLID and unit test. Timely DI with Factory Promise this is last then I will go back to my projects to apply all what I've learned.

  • @gabrieledetrane6412
    @gabrieledetrane6412 2 года назад +5

    Hi Tim, thank you for this useful explaining of the factory. I have a doubt on the use of Func in DI. It is possible to use directly inside the VehicleFactory constructor an IEnumerable instead of a Func? Why the use of the Func if the implementations of IVehicle are registered as transient?
    Thanks in advance!

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

    Explains exactly what i need for a current issue. Thank you Tim. By the way i loved your Web deb masterclass 👍

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

    Great video Tim! Stopped twice (after the AbstractFactory and the VehicleFactory) to get my hands dirty. Thanks to the way you explained it, it only took me a couple of minutes to get everything going as should (sample style off course 😄)
    Going to dive into that Dependency Injection course as well, cheers! 🙏

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

      Great job practicing what you are learning.

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

    Finally someone explained it Thank you 👍

  • @MilanDendis
    @MilanDendis 2 года назад +1

    looking forward to the WPF video ;) i face basically the same problem in WinForms and actually i never though about factory pattern to solve the form creation problem, instead i'm using service locator pattern in this particular case. still so much to learn :)

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

      Great!

    • @codefoxtrot
      @codefoxtrot 2 года назад +1

      This is a great comment -- just as most of us (me included) often miss an opportunity to pass a delegate into a method, I feel like the factory pattern is just a larger version of that. Until you are up against a wall of 'how do I inject parameters into a constructor of a class in my DI container', sometimes you just don't think about... hey wait a minute, I could inject a factory that instantiates my class with params, and then just request that factory be injected! It's brilliant, complex and simple at the same time!

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

    Thanks Tim for this excellent video.

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

    Hi Tim, as far as I understand, there can be a slight issue with the way it is implemented here. On minute 57:20 you show how you create a specific instance of IVehicle. The slight issue I see here is that for any specific IVehicle, the dependency resolver will instantiate all the IVehicles that are defined. So if you have a loop and every time you request a different IVehicle you are actually instantiating all of them.
    The way I did it was to create a factory class as a scoped dependency that accepts all the different instances, and in this case, although for every request I instantiate all of them (like all of IVehicle) I do it only once. I did not make the factory singleton though, because in my case, my instances depended on other scoped dependencies and therefore they had to be scoped as well.

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

      It has been a while, but I believe we actually wanted them to be instantiated once per call.

  • @nedames3328
    @nedames3328 2 года назад +1

    Respect, man. As a long-time Java developer and former C# MVP, just getting back into the DotNet tech stack after 10 years plus, I find your presentations very useful. Even your sidebar comments provide clear and complete information. I learned about Serilog in one of your sidebars. I was wondering how to do structured logging in C#. You explained the basics in just a few minutes. I look forward to seeing more of your presentations.Thank you for your contributions to the software developer community.
    P.S. Loved your newbie caution: "Yes, this is cool", "No don't use it everywhere."

  • @Sanabalis
    @Sanabalis 2 года назад +4

    An amazing video, thank you so much. However, I can't figure out how to do factory pattern with DI (without doing service locator) which can choose between different implementations of the same interface, ie. I have several message handlers, and I have to create the correct one based on the format of the input message (plain text, json, xml..). I managed to do something with IEnumerable, however, that creates all the mssage handlers and then I can choose from them, which can be costly if the construction is expensive. I was thinking to try IEnumerable of factories, and I couldn't get it to work quite right. And my Google-fu also failed to give any results :( Any hints (or a new video) would be highly appreciated.
    Thanks

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

    Fantastic explanations!

  • @Ahmet-nd5ct
    @Ahmet-nd5ct 2 года назад

    WOW! this is wonderful tutorial. 🙏🙏🙏

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

    Great, your awesome my friend, this type of concept works better in big application!

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

      It isn't about the size of the application; it is about the needs of the application. For instance, next week I will show off a small application that needs the factory pattern to properly work.

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

      @@IAmTimCorey thanks for taking your time and respond

  • @jellz77
    @jellz77 2 года назад +1

    Omg I’ve been waiting for exactly this! Thanks for what you do 🙏

  • @XXnickles
    @XXnickles 2 года назад +5

    Factories (especially abstracts) is one of those patterns that I tend to avoid as much as possible. In my opinion, there is nothing worse than add an extra layer of "sorcery" in a code base, and most of the time factories end being just that. Even at the risk of "repeating myself", these days I prefer clarity and expressiveness over "cute engineering"

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

      If I had a Nickle for every time I hear that...

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

      @@seandavidson see what you did there.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +4

      As with anything else in programming, you use it when it is appropriate and don't abuse it. That's why at the end I covered when to use it and how often to use it. I find that I use the factory pattern rarely in development. However, there are times when it is necessary. For instance, I did this video because I've got an upcoming video on WPF dependency injection where I needed to use a factory pattern.

    • @codefoxtrot
      @codefoxtrot 2 года назад +4

      I have to echo Tim here -- maybe you haven't crossed it yet, but there will be a moment where you need to instantiate an object based on some runtime parameters that you just can't wire up in your DI container. The solution will be a factory pattern -- the idea that you can inject a factory class, that will allow you to instantiate an object at runtime, with the params you need to pass it, in order to instantiate an instance of the class you need.

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

      @@codefoxtrot I think this is an important reason of using factory

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

    Hello Tim, thank you very much for the superb explanation and great video. However, in the video, the factory does not take any argument and I would like to know how to pass in an argument to the factory. I have been doing research of my own but so far to no avail (probably wrong keyword).
    One way to implement this is to take another type argument e.g. a struct of an argument and the class declaration and create method will looks like so:
    AbstractFactory.Create(TArg arg) { return _factory(arg); }
    However, i do not know what to code in the service registration.

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

    AbstractFactory name is confusing to me. My intuition was: Abstract = do not instantiate. For me better name is GenericFactory.
    Great video - as usual :)

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

      The thing is the term "abstract factory" is not a C#-specific term. It is an industry term for the pattern that we are applying in C#. So, the term cannot reference C#-specific items (like generics) in the name.

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

    Great Video, Design Patterns are interesting ....👍👍

  • @aleckpups9844
    @aleckpups9844 4 месяца назад

    Thank you for explaining it so well. One question - when I try to get the sample source code, the email functionality doesn't work, i.e. doesn't send anything. I checked the junk folder, but there's nothing either.

    • @IAmTimCorey
      @IAmTimCorey  4 месяца назад +1

      I'm at a conference right now, but I am working on a fix that should be out soon.

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

    I really love your videos but this one is FANTASTIC. Thank you to explain how to proper implement a factory. =]

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

    Thx Tim. Great video. i have a question... why Singleton?

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

      For the factory? Because we don't need multiple instances of it when one will do.

  • @lewisbass-y4m
    @lewisbass-y4m Год назад

    I appreciate this video very much. Do you have one with WPF core that injects a UserControl - where the UserControl has a dependency?

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

    Hello Tim. You're just great! Anyway I don't understand properly the usage of AbstractFactory. If I understand well the code, there is no some kind of intelligence there which can choose between some concrete classes. I'd rather think it's more useful the vehicleFactory. Am I wrong? Thanks a lot

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

    Thank you! The best video on factory pattern with dependency injection so far!! :) Just one question: what would be a more robust method to add new IVehicle implementations without having to use a string to identify the vehicle implementation to create and also not using an enum( that should be modified each time adding new values)?

  • @kuro-rj8md
    @kuro-rj8md 10 месяцев назад

    Hey Tim, when talking about factory pattern we usually mean it as abstract factory pattern or factory method pattern?

    • @IAmTimCorey
      @IAmTimCorey  10 месяцев назад +2

      We were just talking about the factory pattern here, but the reality is that all three do something very similar: stackoverflow.com/a/13030163/733798

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

    Hi Tim. First of all, thank you very much for all this work ! I want to know, if this is a good thing for Mapper. I mean a MapperFactory, with a Map method allows you to map a DTO to an Entity or Entity to a DTO ? Thx again !

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

    Worth using a good DI package like autofac to offload this work where possible.

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

      It can be, if you need those features.

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

    This nicely explains a lot about the workings of the DI container on the new NET6, thanks for this.
    I have a question, you used @Inject as a keyword to call the DI container and to get the needed dependencies. This was done on a razor class, so I suppose such keyword doesn't work in regular classes
    How do you do that in a regular class buried several layers deep into composition?. Suppose i want to share a logger among all my classes. The usual and novice way to do it is to cascade down (thru constructors) the logger instance until the very last class which needs it.
    How do you call the DI from such depths?

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +2

      When you use dependency injection in "normal" classes, you use constructor injection. You just ask for whatever thing you want and dependency injection ensures that you get it (even if the class is multiple levels in).

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

      ​@@IAmTimCorey That is where I get stuck. The first class where i often manage to get dependencies injected is a controller. If such controller needs to perform some business logic which is done in another class (lets call it Class A), such class can be instantiated in Controller's constructor, taking advantage of the services injected to it. The problem arises if Class A depends on other resources located deeper in other classes.
      I don't know how to make the DI container "aware" of Class A needing to instantiate a Class B or Class C for that matter. Unless i'm not getting it right and the whole goal of DI is to setup everyting in the constructor of the first place where dependencies are injected, this is, the controller.
      Thank you, as always :D

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

      The controller would have a dependency on Class A, so it would ask for Class A in the constructor. Class A would have a dependency on Class B, so Class A would ask for Class B in the constructor. And so on it goes. No one instantiates a class on their own. They all just ask the dependency injection system for the class instances they need.

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

    Great! Are you going to be covering more such things? Thank you for this!

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +2

      I cover most C# topics, so probably.

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

      @@IAmTimCorey really appreciate series of videos you post. Thank you. Much love from India.

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

    it's a pity that none of your end classes like car etc. hand no constructor parameters, it would be cool to see how to tackle that, also what is the point of passing func to the factory constructor ? i think it's just easier to do new in the factory, the problem with func is that if your class takes some parameters in constructor you need to have them in func as well and it becomes messy and not readable. If your factory implements interface already i think it's ok to use new in the factory without passing func to it.

  • @Jhv-x4o
    @Jhv-x4o 2 года назад

    Thanks!

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

    Can someone explain the right implementation of the last example?

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

    Hi Tim, thank you for video. I am not sure about AddGenericClassWithDataFactory class, you call it factory. Dou you mean factory method or factory method is something different from this AddGenericClassWithDataFactory factory class? AbstractFactory.cs class is clear abstract factory.

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

      I'm not sure I understand your question. A "factory" is a design pattern that you implement. The name "Factory" in the class name indicates that the class is a factory.

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

      @@IAmTimCorey Thank you for your answer. I found now tree different design patterns. Factory, factory method and abstract factory. I didn’t know difference between factory an factory method. I thought that only two design patterns exists , factory method and abstract factory. I also thought that factory method and factory are the same in your video and you just name it as factory. But I see that factory is third design patter that i didn’t know that exist.

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

    Fantastic video as always. Hey Tim. Got a question for you. Is there anyway that a controller in blazor webassembly hosted application invoke an event on client side? I am working on implementing file upload and I would like to send progress feedback to client. I was thinking of signalr but it may be too much for what I am trying to achieve here. Any help is much appreciated.

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

      Hmmm, not sure in that scenario.

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

    Thankyou.

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

    One suggestion I would have is if a person needed a factory pattern that is not abstract, that is a good use of source generators. Can take some time to set up. However, once set up, then its very easy to make it like generic even though its not generic so a person does not have repetition. In this case, I would think its better to have extra complexity of the source generator than having to manually do lots of the same code over and over and making just some tweaks.

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +4

      I personally don't recommend source generators for most situations. You are creating source code that you still have to maintain yet isn't created by you directly. When you need to update the code, you need to update the generator, which means you need to debug an extra layer.

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

    Love the video! And how about a factory with an async Create, is that possible?

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

    IAmTimCorey, ok you show how to instantiate objects with dependencies and change properties in factories when it created, but what if you can't resolve dependencies? For example constructor with a string parameter. And you don't show how you can use factories for DI container. Actually they are factory methods, i mean that functions in addTransiand().

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

    This is literally hurting my brain. but I won't give up easily.

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

      Stick with it. If you practice it, sometimes that helps it click.

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

    Isnt Func a lambda expression? a function with no name?
    But delegates we declare a name then late define it of that delegate type?

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

      A lambda expression is an anonymous function. It is not a delegate. However, it can be converted into a delegate directly. So a lambda can be a delegate, but doesn't have to be. A delegate can be a lambda, but doesn't have to be. They are very close.

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

    36:58 Would have been a great place to break this video into two parts. Wrapping the Func inside a factory class is cool and all, but the factory pattern is more useful than this.

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

      That's why I included more of the video - you can do more with the factory than just create multiple instances of a class.

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

      @@IAmTimCorey I'm glad you did, it helps a lot.

  • @dcvsling
    @dcvsling 2 года назад +1

    DI Container already do factory stuff , constructor injection is working in container's factories
    why create other factory outside of container ?

    • @codefoxtrot
      @codefoxtrot 2 года назад +1

      As you get further into C# and DI (compositional programming), sometimes you find yourself in a scenario where you need to inject constructor parameters, at runitime, that you can't pass when you are wiring up your DI system. It's a rare occasion, but when you need it, you absolutely NEED the Factory Pattern. The idea is that you can add a factory class that can instantiate a new object, based on some runtime parameters that you can fill-in. So, you add the factory class to your DI container, and inject the factory class into any other class that depends on it. Once you inject the factory class, now you can instantiate a new object with whatever runtime params you need, and the factory class returns that created object. It's brilliant, but perhaps you haven't bumped into the need for this pattern just yet. But you eventually will.

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

      It isn't often needed, as Brian mentioned. However, if you watch next Monday's video, you will see one case where it is needed.

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

    Is this similar to a repository pattern and do you use a respitory pattern?

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

      No, the factory pattern is different than the repository pattern.

  • @2005bgva
    @2005bgva Год назад

    I was trying to do the same in minute 9:37 but using MVC view, then I created a button wiht a route: asp-route-sample="@sample" but I receive this error: InvalidOperationException: Could not create an instance of type 'ISample'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Record types must have a single primary constructor. Alternatively, give the 'sample' parameter a non-null default value. maybe coudl be a good idea to do the same example but using a MVC template, no Blazor.

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

    Hi Tim, if you have a code behind approach can you navigate me to the url on RUclips please. Again, amazing content

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

      I'm not sure what you mean.

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

    Will you do all patterns? Mostly interested in Builder

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +2

      Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/

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

      @@IAmTimCorey I will. Hopefully it was already on your mind :). I would pay for a complete patterns course.

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

    Tim you're being New()phobic ! 😂😂😂

  • @jee.squared2302
    @jee.squared2302 Год назад

    ???If i applied factory pattern in multiple threading is it thread safe right ? since i am calling new instance every thread and i will not encounter db concurrency?

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

      There is a lot to thread safety but it sounds like you are well on your way to that.

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

    How to create instances of the same implementation with different appsettings configuration values? Is a factory the correct solution for this problem?

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

      No, you just change the appsettings.json file for each implementation. That's the purpose of it - to be externally configurable. When you deploy your application, your build process can change those values. That's what you do to support the Dev/QA/Staging/Prod environments in an automated manner.

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

      @@IAmTimCoreyIn case I have a real abstract factory pattern, how can I inject an abstract factory that creates a family of related products using a parameter obtained from a database? Is it possible to implement this pattern using dependency injection? thank you very much for your work!

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

    Are you part of the C# language team? They have a Tim there, if I recall correctly. Is it you?

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

      Nope. I don’t work for Microsoft. I own my own business.

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

    Hi Tim. If I want to connect to different data providers, for example SQL connection and oledbconnection, i create two repository sqlserverrepository and Oracle repository that inherit from generic repository interface.
    Should I change in every repository the IDBconnection for each different method or create a factory method that choose the idbconnection and create only once repository that get the IDBconnection from this factory?
    Thanks in advance.

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

      I would not create a factory for that. Just ask for whichever type you wanted. That way your dependencies are clear. You are asking for the SQL version in one class and the Oracle in another.

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

      @@IAmTimCorey Thank you very much. Have a good day.

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

    So I've watched a few of your videos on this topic (including this one) and I can't seem to find the answer to a question. What if one of your classes - say Sample2 was using readonly fields so the Sample2 constructor needed to provide those field values
    The below code example you provided wouldn't work in that scenario, would it?
    var output = _factory();
    output.Param = param;
    return output;

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

      You would need to provide those values to the factory and the factory would need to instantiate it with those values.

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

      @@IAmTimCorey I really appreciate you replying. But looking at, for example, the UserDataFactory at 41:45 (ruclips.net/video/2PXAfSfvRKY/видео.html)
      I'm assuming I'd need to pass them into the Create() method correct? I'm under the UserDataFactory constructor isn't something I would change as it's populated entirely by DI. And if I'm understanding that correctly, I'd need to do something with it at line 21?
      var output = _factory()
      Or if you're aware of another video or resource I may have missed I'm happy to rewatch something to save you the explanation, I just wasn't able to find this answer

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

    Shouldn't the VehicleFactory create function return an AbstractFactory? I'm still confused on where to separate a factory of factories and a regular factory.

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

      We don't have a factory of factories. VehicleFactory's job is to return a type of IVehicle. Which instance it returns depends on what the caller wants (Car, Truck, or Van). The end goal of a factory is to create an instance of a requested class. However, just requesting an instance of the interface directly from the constructor won't work for some reason. It may be that we need multiple instances, it may be that we need different concrete types, or it may be that we need the factory to control whether we get a new or recycled instance (like IHttpClientFactory does). The goal isn't to get a factory. The goal is to get the right instance.

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

      @@IAmTimCorey this is a good point. I agree the end user doesn't want to chain calls to create. "factory.Create("Car").Create()" is a bit silly. But I wonder if the vehicle factory should rely on abstract factory to create the car?

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

      Why? How does it add additional value?

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

      @@IAmTimCorey in this example it doesn't but if new Car() needed more setup then maybe the extra layer would be good

  • @村人A-d5h
    @村人A-d5h Год назад

    My company offers English conversation and book purchases, but there is no way to purchase your courses at company fees. Do I have a way to buy your course in English conversation or, books, thanks.

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

      I do not understand what "English conversation" means. My courses are not also books, though.

    • @torrvic1156
      @torrvic1156 2 месяца назад

      As a person with English far from perfect I remembered funny scene fron Pulp Fiction 😂”English motherducker! Can you speak it!?”

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

    Hi Tim, I have a suggestion for a future video. What if you want to make 2 class libraries, or 2 projects, that are independent of each other and can be used by themselves. Let's call them projects A and B. But there's some extra classes or methods that I believe would fit right into B, but that depend on A.
    I'm assuming here that those extra classes and methods are entirely optional and you don't need them to use most of what B has to offer. I want to give the user the opportunity to use those extra classes and methods, but I don't want everyone that uses B to also have to include A in their projects, since not everyone will need those extra functions. What is the best way to do something like that?

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

      They either don't fit with B or B does rely on A. In general terms, it sounds like you actually have a C, which depends on A. Also, if you have a hard dependency and you can't swap it out for something else, put those in the same library and potentially the same class. The separation doesn't actually give you any value. It just adds complexity without a purpose.

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

      @@IAmTimCorey Well, here's the context for what I'm suggesting:
      I want to make a library for Modeling of Rheology, which describe the way materials behave through models that consist of springs, dashpots and masses. From the model we can calculate a number of properties.
      Then, I want to make a library about Modeling of Dynamic Systems, that can calculate and simulate dynamic behaviour of structures through simplified models.
      In theory, the simulation of dynamic behaviour depends on the rheology of the material, but for most practical applications there's a standard model to work with, the Kelvin-Voigt model. As such, you can just give the system some properties that you either measured from experiments or got from literature and solve the system considering the Kelvin-Voigt model through a simple differential equation.
      But, I think it would be cool, and useful, to have a feature where you could give the rheological model you want to use and the library would generate a corresponding dynamic system with the correct properties. Think about it as a constructor overload, where instead of building the DynamicSystemModel with numerical parameters, instead you pass in a RheologicalModel as an argument.
      My debate here is that those two libraries do very different things, even if one is of theoretical importance to the other, so I would like to keep them separate. Maybe this is a case where the Dynamics of the Systems does really depend on the Rheology and as such the dependency is justified, but from a practical point of view, most systems are modeled trough the Kelvin-Voigt model, so this would be a relatively fringe use-case.
      For instance, for a regular simulation using the Kelvin-Voigt model, I probably won't even bother generating a RheologyModel, I'd go directly to the governing equation, since it's more efficient.
      Of course, I'm still on the planning phase, so I'm putting a lot of thought into it, but thanks for the reply.

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

      You could maybe make library C that depends on both A and B and contains extension methods to link them. Alternatively you can make subclasses of A and B classes in C.

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

    For TImplementation, isn't 'class' redundant since TInterface is already restricted to class?

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

      Yes, it is.

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

      @@IAmTimCorey I watched your video yesterday, and today I had a little time to create the test project and follow along.
      If I remove the 'class' restriction from 'TImplementation', leaving just 'TInterface', then I get a red squiggly under 'services.AddTransient();'
      The error is 'The type 'TImplementation' must be a reference type'.
      So I guess it's not redundant after all.
      Your videos are great. I really like the way you can explain things in a clear and easy to understand manner.

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

      Ah, good catch. This is more of a compile-time issue rather than a "real" issue.

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

    Hey Tim, thanks for the great video. I have a question. How would factory injection work if the object you'd like to create is immutable? The code provided as an example wouldn't work:
    var userData = factory.Create();
    userData.Name = name; //this would fail because the object is immutable
    return userData;
    Can we somehow have UserDataFactory have Func injected so we can just return _factory(name) in Create method?

    • @codefoxtrot
      @codefoxtrot 2 года назад +1

      Yes, you absolutely can. There's nothing stopping you from creating a factory class, that just contains a series of overloaded constructors, where each constructor takes some number of params and returns (creates/instantiates) an object based on the params you provide. The idea being, you inject your factory class into whatever class that needs it... and from the instance of your factory class, you call the appropriate constructor (with runtime params) that instantiates the object you need.

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

      @@codefoxtrot hey, thanks for the reply. Can you please show me an example code?

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

      @@m5s10 I replied to this days ago, but looks like it was filtered, probably because it contained reference to a github repo. Can you put up a posting on Tim Corey's forum, and I'll be happy to direct you to an example... please reply back when you do so I get a notification!

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

    Love your show! Unfortunately, that means I may post questions...
    After watching your videos, the true horror of my coding becomes somewhat more clear, but I'd be interested in your take on exactly how horrific it is... :) I started doing a thing with delegates that allowed me to string together a series of actions I wanted to take -- in this case logging actions. The code in question (in a class) looked like:
    class Scanner {
    public delegate void AsyncLogger(int scanID, int sequence, string type, string message);
    public AsyncLogger logger; }
    And I would add one or more logging functions like so (with instantiated class "scan"):
    scan.logger = logtoconsole;
    scan.logger += logtodatabase; // Log entries now are printed and databased.
    This feels like a sort of demonic form of dependency injection...
    Am I doomed to Fortran coding?

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

      It isn't a great substitution for dependency injection, but that doesn't mean you are doomed or anything. Software development is about growth. You learn new techniques, and then you improve your development going forward.

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

      @@IAmTimCorey what would you see as the challenge/downside to this approach vs DI? It seems to avoid the “rewrite all code” issues if I want to add/change loggers, allows me to string multiple logging actions together, and I think I could use factories to supply the delegate(s) if I wanted… is it just that this approach leads to the possibility of not passing in what might be a required dependency?
      In my sample, the logging action or actions are optional, if no logger is passed in the any logging calls just return, but if it were a required dependency…. Maybe “optional dependency” is an oxymoron?

  • @eng.wandeson
    @eng.wandeson 2 года назад

    Very good, Tim! This method it works in .NET 5? It is similar to declaring a new, correct? Can I use it in windows forms without spoiling the performance?

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +4

      Yes, it will work in .NET 5. Actually, it will work in .NET Core 2.1 and above I believe. Dependency injection (DI) is different than declaring a new. When you instantiate a class, you are specifying which concrete type at that spot. That is a dependency. You always have dependencies in code. However, it is hard to change those dependencies if you instantiate them all over. For instance, imagine if you instantiated log4net everywhere that you needed to log something. Then imagine you wanted to switch over to Serilog. How hard would that be? You would need to change every class in your entire project. You may even need to change class libraries where you don't have the source code. With DI, you could change it in one line.
      With Factories, we can continue to use DI even when we need to instantiate a class immediately instead of once at the constructor. This is not something we do often, but it is valuable in certain situations.
      As for performance, the performance is basically the same whether you use DI or not.

    • @eng.wandeson
      @eng.wandeson 2 года назад

      @@IAmTimCorey Thank you very much Tim for you response. Did Help me with my questions. I follow your channel and I learn of lot with you. You're excelent teacther. So, that I wanted say was that, when you inject the depencey injection for construtor of traditional way, she stay disponible and consume resources immediately and this control is at the discretion of the container. This way is much better, why we be controlling it and adjusting our form.
      My question final is: when it comes to windows form, which of the options do you recommend for me to use as default? Example 1, 2 or 3? Remembering that I will work with data. Basically entities, controls, etc. Once again, thank you very much for the reply. I'm talking about Brazil, stay with God!

  • @Richard-jm3um
    @Richard-jm3um 2 года назад

    ❤️

  • @Rajeshsingh-ws5th
    @Rajeshsingh-ws5th 2 года назад

    That's good, can you please make some deep dive vids on block chain?

    • @IAmTimCorey
      @IAmTimCorey  2 года назад +2

      Sorry, no. I don't cover blockchain.

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

    Why is it called abstract factory? My thinkng is that generic factory would be a better name

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

      Patterns are not C#-specific in their names. Design patterns are industry-wide and are named based upon the concept of what they do, not the specific way they are implemented in a language. Here is a link to the description of the abstract factory pattern: www.geeksforgeeks.org/abstract-factory-pattern/

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

    30 mins in to the video, and I dont get it, Usually I never felt this much confused

    • @IAmTimCorey
      @IAmTimCorey  11 месяцев назад +1

      This is a more advanced concept and one that you would benefit from already knowing a lot of the code structures I'm building. It is also one where you would benefit from following along and seeing what the code does yourself.

  • @vladeb1104
    @vladeb1104 8 месяцев назад

    not suitable for .net8 :-(

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

      This code will all work with .NET 8. It will look a little different if you use top-level statements and the new Blazor Web App, but all of the code will still work.

    • @vladeb1104
      @vladeb1104 8 месяцев назад

      @@IAmTimCorey Somethink has to be missing in Program.cs in ready made Blazor WebApp under .net8 as for some reason the delegate is not trigerred based on your impl - have to check the same ready made example under .net6 and perhaps this will help to figure it out

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

    I so hate Blazer bindings. I've written several AngularJS apps where bindings are code less. I understand that it's gone out Of fashion. MS haven't improved web development since classic ASP.

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

    your videos are just too lengthy.. perhaps extremely lengthy.. in this time sensitive world.. please plan it smarter.

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

      You have to look at the purpose of my videos to judge their length. It sounds like you want a "just the facts" 5-10 minute video on a topic. I have those. But they don't really prepare you to actually use a topic in the real world. They just give you the start of the information you need. You don't learn how to integrate it into a larger whole, you don't learn about the best practices around the topic, and you don't learn when to use it and when NOT to use it. Those are things that come in my full training videos (like this one). Those can't be short. So yes, I am planning it smarter. My goal isn't to have the most compact video out there. My goal is to prepare my viewers to actually use a topic intelligently in the real world.

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

    Nice try, nice try to pronounce Blazor, LoL

  • @baturhankahraman426
    @baturhankahraman426 2 года назад +1

    Hey, instead of using as x=> () =>x.GetService()! possibly you can use x=>x.GetServices --- without paranthesis.

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

    Hi Tim! I'm confusing at 56:08, you want to get a service of type IEnumerable "x.GetService()!"
    But you didn't register a service of type IEnumerable. How the DI container know to give you the service you required?

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

      We had registered multiple IVehicle objects. When you ask for an IEnumerable of an object, DI will give you every object that was registered, not just the last one.

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

    I am actually getting an error: aspnetcore-browser-refresh.js:234
    WebSocket connection to 'wss://localhost:44323/FactoryPattern/' failed: Error in connection establishment: net::ERR_CERT_DATE_INVALID Any suggestions?? Followed the steps. Running on Visual Studio 2022, V17.3

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

      It looks like your local development certificate is expired. I think if you run the following two commands in PowerShell that it will clean it up:
      dotnet dev-certs https --clean
      dotnet dev-certs https --trust
      (from stackoverflow.com/a/70291937/733798 )

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

    var appServices = typeof(Program).Assembly.GetTypes()
    .Where(s => s.Name.EndsWith("Service") && s.IsInterface == false).ToList();
    foreach (var appService in appServices)
    builder.Services.Add(new ServiceDescriptor(appService, appService, ServiceLifetime.Scoped));

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

      This adds all services to dependency injection, but it isn't a factory pattern, and it doesn't solve the problem that the factory pattern solves.