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.
@IAmTimCorey2 жыл бұрын
Thanks!
@88spaces2 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
You are welcome.
@mikemcgrumpy2 жыл бұрын
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!
@IAmTimCorey2 жыл бұрын
Thank you!
@TheJessejunior2 жыл бұрын
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!
@IAmTimCorey2 жыл бұрын
You are welcome.
@d3tn3tracer2 жыл бұрын
Thanks Tim. Your videos, education, and entusiasm to help others is so good! Thx a lot Tim.
@IAmTimCorey2 жыл бұрын
Thank you!
@kdcurrin2 жыл бұрын
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!
@IAmTimCorey2 жыл бұрын
You are welcome. Congratulations on the new job!
@danielheydt98642 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
I am glad it was so helpful.
@asahajitdalui1962 Жыл бұрын
❤ From India. No matter how much knowledge a person have teaching someone is an Art. Appreciate your effort.
@IAmTimCorey Жыл бұрын
Thank you!
@irlonterblanche16392 жыл бұрын
Wow, I'm only 13 minutes into this video, and already you have clarified so much! Thank you for making a difference!
@IAmTimCorey2 жыл бұрын
You're so welcome!
@sammynochains34552 жыл бұрын
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 ..
@IAmTimCorey2 жыл бұрын
You are welcome.
@runtimmytimer2 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
Thank you!
@JoeEnos2 жыл бұрын
Fantastic explanations!
@IAmTimCorey2 жыл бұрын
Thank you!
@upcsatx2 жыл бұрын
Your abstract factory is truly an elegant bit of code. Thanks for posting!
@IAmTimCorey2 жыл бұрын
Glad you like it!
@krishnamurthymadaraboina15569 ай бұрын
i was trying to write a factory with dependency injection, this helped me. thank you
@IAmTimCorey9 ай бұрын
Glad it helped!
@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 Жыл бұрын
It has been a while, but I believe we actually wanted them to be instantiated once per call.
@camcommute2 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
Great!
@gabrieledetrane64122 жыл бұрын
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!
@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.
@err_0-5rZ2 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
Awesome!
@williameduardo70202 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
Thanks!
@jakubdedio54212 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
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.
@jakubdedio54212 жыл бұрын
@@IAmTimCorey Ahh. So much to learn! Thank you for your time and answer ☺️
@JoeBonez2 жыл бұрын
I have never considered this use of Func before. Very good info, thanks.
@IAmTimCorey2 жыл бұрын
You are welcome.
@codefoxtrot2 жыл бұрын
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!
@scottprokopetz70982 жыл бұрын
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! 😊
@IAmTimCorey2 жыл бұрын
I am glad it was so helpful.
@Sanabalis2 жыл бұрын
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
@viniciustrindade6675 Жыл бұрын
Tim, please make videos about the other design patterns!!! love from brazil
@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/
@neopro6882 жыл бұрын
very good video, open my mind when you show funcs in injection dependency injection.
@IAmTimCorey2 жыл бұрын
Excellent!
@XXnickles2 жыл бұрын
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"
@seandavidson2 жыл бұрын
If I had a Nickle for every time I hear that...
@vbaclasses35532 жыл бұрын
@@seandavidson see what you did there.
@IAmTimCorey2 жыл бұрын
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.
@codefoxtrot2 жыл бұрын
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.
@johnnguyen16552 жыл бұрын
@@codefoxtrot I think this is an important reason of using factory
@hassanmehmood46862 жыл бұрын
Finally someone explained it Thank you 👍
@IAmTimCorey2 жыл бұрын
You are welcome.
@mbrotto1970 Жыл бұрын
Explains exactly what i need for a current issue. Thank you Tim. By the way i loved your Web deb masterclass 👍
@IAmTimCorey Жыл бұрын
Thanks for sharing!
@jellz772 жыл бұрын
Omg I’ve been waiting for exactly this! Thanks for what you do 🙏
@IAmTimCorey2 жыл бұрын
You are welcome.
@joericeulemans10682 жыл бұрын
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! 🙏
@IAmTimCorey2 жыл бұрын
Great job practicing what you are learning.
@MilanDendis2 жыл бұрын
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 :)
@IAmTimCorey2 жыл бұрын
Great!
@codefoxtrot2 жыл бұрын
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!
@nedames33282 жыл бұрын
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."
@IAmTimCorey2 жыл бұрын
Thanks!
@bulldogavenue2 жыл бұрын
Thanks Tim for this excellent video.
@IAmTimCorey2 жыл бұрын
You are welcome.
@haroldpepete2 жыл бұрын
Great, your awesome my friend, this type of concept works better in big application!
@IAmTimCorey2 жыл бұрын
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.
@haroldpepete2 жыл бұрын
@@IAmTimCorey thanks for taking your time and respond
@longuinni2 жыл бұрын
I really love your videos but this one is FANTASTIC. Thank you to explain how to proper implement a factory. =]
@IAmTimCorey2 жыл бұрын
You're very welcome!
@crazyfox552 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
That's why I included more of the video - you can do more with the factory than just create multiple instances of a class.
@crazyfox552 жыл бұрын
@@IAmTimCorey I'm glad you did, it helps a lot.
@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.
@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.
@andywalter74262 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
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.
@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 !
@Ahmet-nd5ct2 жыл бұрын
WOW! this is wonderful tutorial. 🙏🙏🙏
@IAmTimCorey2 жыл бұрын
Thanks!
@alessandrocroci83792 жыл бұрын
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)?
@antonofka90182 жыл бұрын
a registry or static guid's
@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?
@IAmTimCorey Жыл бұрын
I don't believe so. Not yet.
@danielgontarek33942 жыл бұрын
AbstractFactory name is confusing to me. My intuition was: Abstract = do not instantiate. For me better name is GenericFactory. Great video - as usual :)
@IAmTimCorey2 жыл бұрын
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.
@aleckpups98445 ай бұрын
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.
@IAmTimCorey5 ай бұрын
I'm at a conference right now, but I am working on a fix that should be out soon.
@saminajjar57672 жыл бұрын
Great Video, Design Patterns are interesting ....👍👍
@IAmTimCorey2 жыл бұрын
Thank you!
@alessandrovangeli83952 жыл бұрын
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
@puntoycoma472 жыл бұрын
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?
@IAmTimCorey2 жыл бұрын
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).
@puntoycoma472 жыл бұрын
@@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
@IAmTimCorey2 жыл бұрын
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.
@after20032 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
Hmmm, not sure in that scenario.
@mortezanejat87072 жыл бұрын
Thx Tim. Great video. i have a question... why Singleton?
@IAmTimCorey2 жыл бұрын
For the factory? Because we don't need multiple instances of it when one will do.
@kuro-rj8md10 ай бұрын
Hey Tim, when talking about factory pattern we usually mean it as abstract factory pattern or factory method pattern?
@IAmTimCorey10 ай бұрын
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
@alfonsdeda89122 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
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.
@alfonsdeda89122 жыл бұрын
@@IAmTimCorey Thank you very much. Have a good day.
@ViragDesai2 жыл бұрын
Great! Are you going to be covering more such things? Thank you for this!
@IAmTimCorey2 жыл бұрын
I cover most C# topics, so probably.
@ViragDesai2 жыл бұрын
@@IAmTimCorey really appreciate series of videos you post. Thank you. Much love from India.
@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 Жыл бұрын
There is a lot to thread safety but it sounds like you are well on your way to that.
@AlThePal782 жыл бұрын
Is this similar to a repository pattern and do you use a respitory pattern?
@IAmTimCorey2 жыл бұрын
No, the factory pattern is different than the repository pattern.
@Romahotmetytky2 ай бұрын
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.
@crazyfox552 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
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.
@crazyfox552 жыл бұрын
@@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?
@IAmTimCorey2 жыл бұрын
Why? How does it add additional value?
@crazyfox552 жыл бұрын
@@IAmTimCorey in this example it doesn't but if new Car() needed more setup then maybe the extra layer would be good
@coderider30222 жыл бұрын
Worth using a good DI package like autofac to offload this work where possible.
@IAmTimCorey2 жыл бұрын
It can be, if you need those features.
@村人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 Жыл бұрын
I do not understand what "English conversation" means. My courses are not also books, though.
@torrvic11562 ай бұрын
As a person with English far from perfect I remembered funny scene fron Pulp Fiction 😂”English motherducker! Can you speak it!?”
@ivanstoskovic38162 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
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.
@ivanstoskovic38162 жыл бұрын
@@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.
@dcvsling2 жыл бұрын
DI Container already do factory stuff , constructor injection is working in container's factories why create other factory outside of container ?
@codefoxtrot2 жыл бұрын
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.
@IAmTimCorey2 жыл бұрын
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.
@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 Жыл бұрын
You would need to provide those values to the factory and the factory would need to instantiate it with those values.
@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
@m5s102 жыл бұрын
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?
@codefoxtrot2 жыл бұрын
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.
@m5s102 жыл бұрын
@@codefoxtrot hey, thanks for the reply. Can you please show me an example code?
@codefoxtrot2 жыл бұрын
@@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!
@rferreiraperez79562 жыл бұрын
How to create instances of the same implementation with different appsettings configuration values? Is a factory the correct solution for this problem?
@IAmTimCorey2 жыл бұрын
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 Жыл бұрын
@@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!
@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 Жыл бұрын
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.
@idenardi2 жыл бұрын
Love the video! And how about a factory with an async Create, is that possible?
@marcusmaunula50182 жыл бұрын
Will you do all patterns? Mostly interested in Builder
@IAmTimCorey2 жыл бұрын
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/
@marcusmaunula50182 жыл бұрын
@@IAmTimCorey I will. Hopefully it was already on your mind :). I would pay for a complete patterns course.
@ashleygahl36382 жыл бұрын
Hi Tim, if you have a code behind approach can you navigate me to the url on KZbin please. Again, amazing content
@IAmTimCorey2 жыл бұрын
I'm not sure what you mean.
@mattaku9430 Жыл бұрын
Can someone explain the right implementation of the last example?
@efimov902 жыл бұрын
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().
@KakoriGames2 жыл бұрын
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?
@IAmTimCorey2 жыл бұрын
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.
@KakoriGames2 жыл бұрын
@@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.
@phizc2 жыл бұрын
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.
@waliqadri Жыл бұрын
This is literally hurting my brain. but I won't give up easily.
@IAmTimCorey Жыл бұрын
Stick with it. If you practice it, sometimes that helps it click.
@jamesdraughn50722 жыл бұрын
For TImplementation, isn't 'class' redundant since TInterface is already restricted to class?
@IAmTimCorey2 жыл бұрын
Yes, it is.
@jamesdraughn50722 жыл бұрын
@@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.
@IAmTimCorey2 жыл бұрын
Ah, good catch. This is more of a compile-time issue rather than a "real" issue.
@boohica2 жыл бұрын
Tim you're being New()phobic ! 😂😂😂
@IAmTimCorey2 жыл бұрын
Absolutely.
@Jhv-x4o2 жыл бұрын
Thanks!
@IAmTimCorey2 жыл бұрын
You are welcome.
@eng.wandeson2 жыл бұрын
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?
@IAmTimCorey2 жыл бұрын
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.wandeson2 жыл бұрын
@@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!
@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 Жыл бұрын
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 Жыл бұрын
@@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?
@juliankohler508610 ай бұрын
Are you part of the C# language team? They have a Tim there, if I recall correctly. Is it you?
@IAmTimCorey10 ай бұрын
Nope. I don’t work for Microsoft. I own my own business.
@vivekkaushik95082 жыл бұрын
Thankyou.
@IAmTimCorey2 жыл бұрын
You are welcome.
@Richard-jm3um2 жыл бұрын
❤️
@IAmTimCorey2 жыл бұрын
😀
@LindenMikus2 жыл бұрын
Why is it called abstract factory? My thinkng is that generic factory would be a better name
@IAmTimCorey2 жыл бұрын
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/
@Rajeshsingh-ws5th2 жыл бұрын
That's good, can you please make some deep dive vids on block chain?
@IAmTimCorey2 жыл бұрын
Sorry, no. I don't cover blockchain.
@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.
@msiva1910 Жыл бұрын
30 mins in to the video, and I dont get it, Usually I never felt this much confused
@IAmTimCorey Жыл бұрын
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.
@vladeb11049 ай бұрын
not suitable for .net8 :-(
@IAmTimCorey9 ай бұрын
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.
@vladeb11049 ай бұрын
@@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
@sivasagarjagga64452 жыл бұрын
your videos are just too lengthy.. perhaps extremely lengthy.. in this time sensitive world.. please plan it smarter.
@IAmTimCorey2 жыл бұрын
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.
@zikkrype2 жыл бұрын
Nice try, nice try to pronounce Blazor, LoL
@IAmTimCorey2 жыл бұрын
Huh?
@nguyenhoan32182 жыл бұрын
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?
@IAmTimCorey2 жыл бұрын
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.
@baturhankahraman4262 жыл бұрын
Hey, instead of using as x=> () =>x.GetService()! possibly you can use x=>x.GetServices --- without paranthesis.
@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 Жыл бұрын
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 )
@MohammadKomaei2 жыл бұрын
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));
@IAmTimCorey2 жыл бұрын
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.