Factory Pattern in C# with Dependency Injection

  Рет қаралды 101,807

IAmTimCorey

IAmTimCorey

Жыл бұрын

In dependency injection, we typically put our dependencies in the constructor. When our class is created, our dependencies get created and injected. However, there are times when we want to create our dependencies more often or in different ways. One solution for this is the factory pattern. In this video, we are going to look at how to create factories for our various needs in C#. We will look at an abstract factory, a factory for initializing class instances with startup data, and a factory for instantiating different implementation classes based upon passed in parameters. With each solution, we will be implementing it inside of dependency injection for proper handling of dependencies.
Full Training Courses: IAmTimCorey.com
Source Code: leadmagnets.app/?Resource=Fac...
Mailing List: signup.iamtimcorey.com/

Пікірлер: 203
@88spaces
@88spaces Жыл бұрын
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.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thanks!
@mikemcgrumpy
@mikemcgrumpy Жыл бұрын
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!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thank you!
@88spaces
@88spaces Жыл бұрын
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.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@TheJessejunior
@TheJessejunior Жыл бұрын
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!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@d3tn3tracer
@d3tn3tracer Жыл бұрын
Thanks Tim. Your videos, education, and entusiasm to help others is so good! Thx a lot Tim.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thank you!
@upcsatx
@upcsatx Жыл бұрын
Your abstract factory is truly an elegant bit of code. Thanks for posting!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Glad you like it!
@irlonterblanche1639
@irlonterblanche1639 Жыл бұрын
Wow, I'm only 13 minutes into this video, and already you have clarified so much! Thank you for making a difference!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You're so welcome!
@danielheydt9864
@danielheydt9864 Жыл бұрын
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 Жыл бұрын
I am glad it was so helpful.
@sammynochains3455
@sammynochains3455 Жыл бұрын
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 ..
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@runtimmytimer
@runtimmytimer Жыл бұрын
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.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thank you!
@jellz77
@jellz77 Жыл бұрын
Omg I’ve been waiting for exactly this! Thanks for what you do 🙏
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@kdcurrin
@kdcurrin Жыл бұрын
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 Жыл бұрын
You are welcome. Congratulations on the new job!
@asahajitdalui1962
@asahajitdalui1962 Жыл бұрын
❤ From India. No matter how much knowledge a person have teaching someone is an Art. Appreciate your effort.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thank you!
@scottprokopetz7098
@scottprokopetz7098 Жыл бұрын
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 Жыл бұрын
I am glad it was so helpful.
@krishnamurthymadaraboina1556
@krishnamurthymadaraboina1556 3 ай бұрын
i was trying to write a factory with dependency injection, this helped me. thank you
@IAmTimCorey
@IAmTimCorey 3 ай бұрын
Glad it helped!
@mbrotto1970
@mbrotto1970 8 ай бұрын
Explains exactly what i need for a current issue. Thank you Tim. By the way i loved your Web deb masterclass 👍
@IAmTimCorey
@IAmTimCorey 8 ай бұрын
Thanks for sharing!
@longuinni
@longuinni Жыл бұрын
I really love your videos but this one is FANTASTIC. Thank you to explain how to proper implement a factory. =]
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You're very welcome!
@williameduardo7020
@williameduardo7020 Жыл бұрын
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.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thanks!
@bulldogavenue
@bulldogavenue Жыл бұрын
Thanks Tim for this excellent video.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@hassanmehmood4686
@hassanmehmood4686 Жыл бұрын
Finally someone explained it Thank you 👍
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@Ahmet-nd5ct
@Ahmet-nd5ct Жыл бұрын
WOW! this is wonderful tutorial. 🙏🙏🙏
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thanks!
@JoeBonez
@JoeBonez Жыл бұрын
I have never considered this use of Func before. Very good info, thanks.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@codefoxtrot
@codefoxtrot Жыл бұрын
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!
@JoeEnos
@JoeEnos Жыл бұрын
Fantastic explanations!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thank you!
@joericeulemans1068
@joericeulemans1068 Жыл бұрын
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 Жыл бұрын
Great job practicing what you are learning.
@haroldpepete
@haroldpepete Жыл бұрын
Great, your awesome my friend, this type of concept works better in big application!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
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 Жыл бұрын
@@IAmTimCorey thanks for taking your time and respond
@neopro688
@neopro688 Жыл бұрын
very good video, open my mind when you show funcs in injection dependency injection.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Excellent!
@devian3634
@devian3634 Жыл бұрын
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.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Awesome!
@gabrieledetrane6412
@gabrieledetrane6412 Жыл бұрын
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!
@viniciustrindade6675
@viniciustrindade6675 Жыл бұрын
Tim, please make videos about the other design patterns!!! love from brazil
@IAmTimCorey
@IAmTimCorey Жыл бұрын
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/
@nedames3328
@nedames3328 Жыл бұрын
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."
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thanks!
@saminajjar5767
@saminajjar5767 Жыл бұрын
Great Video, Design Patterns are interesting ....👍👍
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thank you!
@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 !
@David-rz4vc
@David-rz4vc Жыл бұрын
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.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Great!
@MilanDendis
@MilanDendis Жыл бұрын
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 Жыл бұрын
Great!
@codefoxtrot
@codefoxtrot Жыл бұрын
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!
@jakubdedio5421
@jakubdedio5421 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@IAmTimCorey Ahh. So much to learn! Thank you for your time and answer ☺️
@Sanabalis
@Sanabalis Жыл бұрын
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
@alessandrocroci8379
@alessandrocroci8379 Жыл бұрын
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)?
@antonofka9018
@antonofka9018 Жыл бұрын
a registry or static guid's
@idenardi
@idenardi Жыл бұрын
Love the video! And how about a factory with an async Create, is that possible?
@user-dw4hm9wi9f
@user-dw4hm9wi9f 11 ай бұрын
I appreciate this video very much. Do you have one with WPF core that injects a UserControl - where the UserControl has a dependency?
@IAmTimCorey
@IAmTimCorey 11 ай бұрын
I don't believe so. Not yet.
@user-zf6sl1lv1c
@user-zf6sl1lv1c Жыл бұрын
Thanks!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@ViragDesai
@ViragDesai Жыл бұрын
Great! Are you going to be covering more such things? Thank you for this!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
I cover most C# topics, so probably.
@ViragDesai
@ViragDesai Жыл бұрын
@@IAmTimCorey really appreciate series of videos you post. Thank you. Much love from India.
@alessandrovangeli8395
@alessandrovangeli8395 Жыл бұрын
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
@after2003
@after2003 Жыл бұрын
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 Жыл бұрын
Hmmm, not sure in that scenario.
@coderider3022
@coderider3022 Жыл бұрын
Worth using a good DI package like autofac to offload this work where possible.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
It can be, if you need those features.
@vivekkaushik9508
@vivekkaushik9508 Жыл бұрын
Thankyou.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@XXnickles
@XXnickles Жыл бұрын
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 Жыл бұрын
If I had a Nickle for every time I hear that...
@vbaclasses3553
@vbaclasses3553 Жыл бұрын
@@seandavidson see what you did there.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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.
@mortezanejat8707
@mortezanejat8707 Жыл бұрын
Thx Tim. Great video. i have a question... why Singleton?
@IAmTimCorey
@IAmTimCorey Жыл бұрын
For the factory? Because we don't need multiple instances of it when one will do.
@kuro-rj8md
@kuro-rj8md 4 ай бұрын
Hey Tim, when talking about factory pattern we usually mean it as abstract factory pattern or factory method pattern?
@IAmTimCorey
@IAmTimCorey 4 ай бұрын
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
@eng.wandeson
@eng.wandeson Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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!
@alfonsdeda8912
@alfonsdeda8912 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@IAmTimCorey Thank you very much. Have a good day.
@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.
@danielgontarek3394
@danielgontarek3394 Жыл бұрын
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 Жыл бұрын
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.
@puntoycoma47
@puntoycoma47 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
​@@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 Жыл бұрын
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.
@m5s10
@m5s10 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@codefoxtrot hey, thanks for the reply. Can you please show me an example code?
@codefoxtrot
@codefoxtrot Жыл бұрын
@@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!
@AlThePal78
@AlThePal78 Жыл бұрын
Is this similar to a repository pattern and do you use a respitory pattern?
@IAmTimCorey
@IAmTimCorey Жыл бұрын
No, the factory pattern is different than the repository pattern.
@mattaku9430
@mattaku9430 Жыл бұрын
Can someone explain the right implementation of the last example?
@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 Жыл бұрын
There is a lot to thread safety but it sounds like you are well on your way to that.
@playonce4186
@playonce4186 8 ай бұрын
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 8 ай бұрын
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.
@andywalter7426
@andywalter7426 Жыл бұрын
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 Жыл бұрын
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.
@2005bgva
@2005bgva 10 ай бұрын
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.
@ivanstoskovic3816
@ivanstoskovic3816 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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.
@crazyfox55
@crazyfox55 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
Why? How does it add additional value?
@crazyfox55
@crazyfox55 Жыл бұрын
@@IAmTimCorey in this example it doesn't but if new Car() needed more setup then maybe the extra layer would be good
@marcusmaunula5018
@marcusmaunula5018 Жыл бұрын
Will you do all patterns? Mostly interested in Builder
@IAmTimCorey
@IAmTimCorey Жыл бұрын
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 Жыл бұрын
@@IAmTimCorey I will. Hopefully it was already on your mind :). I would pay for a complete patterns course.
@jamesdraughn5072
@jamesdraughn5072 Жыл бұрын
For TImplementation, isn't 'class' redundant since TInterface is already restricted to class?
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Yes, it is.
@jamesdraughn5072
@jamesdraughn5072 Жыл бұрын
@@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 Жыл бұрын
Ah, good catch. This is more of a compile-time issue rather than a "real" issue.
@ashleygahl3638
@ashleygahl3638 Жыл бұрын
Hi Tim, if you have a code behind approach can you navigate me to the url on KZbin please. Again, amazing content
@IAmTimCorey
@IAmTimCorey Жыл бұрын
I'm not sure what you mean.
@rferreiraperez7956
@rferreiraperez7956 Жыл бұрын
How to create instances of the same implementation with different appsettings configuration values? Is a factory the correct solution for this problem?
@IAmTimCorey
@IAmTimCorey Жыл бұрын
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!
@user-tq7ci3wd2z
@user-tq7ci3wd2z 8 ай бұрын
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 8 ай бұрын
I do not understand what "English conversation" means. My courses are not also books, though.
@waliqadri
@waliqadri 9 ай бұрын
This is literally hurting my brain. but I won't give up easily.
@IAmTimCorey
@IAmTimCorey 9 ай бұрын
Stick with it. If you practice it, sometimes that helps it click.
@Richard-jm3um
@Richard-jm3um Жыл бұрын
❤️
@IAmTimCorey
@IAmTimCorey Жыл бұрын
😀
@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 Жыл бұрын
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 (kzbin.info/www/bejne/aIG7cpmJm9uFgbs) 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
@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 Жыл бұрын
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?
@boohica
@boohica Жыл бұрын
Tim you're being New()phobic ! 😂😂😂
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Absolutely.
@crazyfox55
@crazyfox55 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@IAmTimCorey I'm glad you did, it helps a lot.
@dcvsling
@dcvsling Жыл бұрын
DI Container already do factory stuff , constructor injection is working in container's factories why create other factory outside of container ?
@codefoxtrot
@codefoxtrot Жыл бұрын
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 Жыл бұрын
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.
@KakoriGames
@KakoriGames Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
@@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 Жыл бұрын
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.
@efimov90
@efimov90 Жыл бұрын
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().
@Rajeshsingh-ws5th
@Rajeshsingh-ws5th Жыл бұрын
That's good, can you please make some deep dive vids on block chain?
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Sorry, no. I don't cover blockchain.
@juliankohler5086
@juliankohler5086 4 ай бұрын
Are you part of the C# language team? They have a Tim there, if I recall correctly. Is it you?
@IAmTimCorey
@IAmTimCorey 4 ай бұрын
Nope. I don’t work for Microsoft. I own my own business.
@LindenMikus
@LindenMikus Жыл бұрын
Why is it called abstract factory? My thinkng is that generic factory would be a better name
@IAmTimCorey
@IAmTimCorey Жыл бұрын
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/
@nickbarton3191
@nickbarton3191 6 ай бұрын
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.
@msiva1910
@msiva1910 6 ай бұрын
30 mins in to the video, and I dont get it, Usually I never felt this much confused
@IAmTimCorey
@IAmTimCorey 5 ай бұрын
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 2 ай бұрын
not suitable for .net8 :-(
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
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 2 ай бұрын
@@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
@sivasagarjagga6445
@sivasagarjagga6445 Жыл бұрын
your videos are just too lengthy.. perhaps extremely lengthy.. in this time sensitive world.. please plan it smarter.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
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 Жыл бұрын
Nice try, nice try to pronounce Blazor, LoL
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Huh?
@baturhankahraman426
@baturhankahraman426 Жыл бұрын
Hey, instead of using as x=> () =>x.GetService()! possibly you can use x=>x.GetServices --- without paranthesis.
@nguyenhoan3218
@nguyenhoan3218 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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 Жыл бұрын
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.
C# Dependency Injection with Autofac
54:45
IAmTimCorey
Рет қаралды 291 М.
狼来了的故事你们听过吗?#天使 #小丑 #超人不会飞
00:42
超人不会飞
Рет қаралды 62 МЛН
Super sport🤯
00:15
Lexa_Merin
Рет қаралды 20 МЛН
Pray For Palestine 😢🇵🇸|
00:23
Ak Ultra
Рет қаралды 34 МЛН
Factory Method Pattern - Design Patterns (ep 4)
27:21
Christopher Okhravi
Рет қаралды 532 М.
Dependency Injection in .NET Core (.NET 6)
1:00:32
IAmTimCorey
Рет қаралды 180 М.
5 Design Patterns That Are ACTUALLY Used By Developers
9:27
Alex Hyett
Рет қаралды 175 М.
What is the Factory Pattern? | Software Design Principles
26:48
Be A Better Dev
Рет қаралды 27 М.