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.
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!
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!
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!
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.
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.
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!
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.
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.
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.
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.
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! 😊
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.
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!
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! 🙏
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 :)
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!
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.
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."
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
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.
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"
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.
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.
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.
AbstractFactory name is confusing to me. My intuition was: Abstract = do not instantiate. For me better name is GenericFactory. Great video - as usual :)
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.
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.
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
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)?
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 !
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?
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).
@@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
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.
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.
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.
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.
@@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.
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.
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.
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.
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().
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.
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.
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.
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.
???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?
How to create instances of the same implementation with different appsettings configuration values? Is a factory the correct solution for this problem?
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.
@@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!
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.
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.
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 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
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.
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.
@@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?
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.
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?
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.
@@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.
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.
@@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.
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?
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 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!
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?
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.
@@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?
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?
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.
@@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!
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/
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.
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.
@@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
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.
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.
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?
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.
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
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 )
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.
Thanks!
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.
You are welcome.
❤ From India. No matter how much knowledge a person have teaching someone is an Art. Appreciate your effort.
Thank you!
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!
You are welcome.
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!
You are welcome. Congratulations on the new job!
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!
Thank you!
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 ..
You are welcome.
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.
I am glad it was so helpful.
Wow, I'm only 13 minutes into this video, and already you have clarified so much! Thank you for making a difference!
You're so welcome!
i was trying to write a factory with dependency injection, this helped me. thank you
Glad it helped!
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.
Thank you!
Your abstract factory is truly an elegant bit of code. Thanks for posting!
Glad you like it!
Thanks Tim. Your videos, education, and entusiasm to help others is so good! Thx a lot Tim.
Thank you!
I have never considered this use of Func before. Very good info, thanks.
You are welcome.
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!
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.
very good video, open my mind when you show funcs in injection dependency injection.
Excellent!
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.
Great!
Tim, please make videos about the other design patterns!!! love from brazil
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/
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.
Thanks!
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.
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.
@@IAmTimCorey Ahh. So much to learn! Thank you for your time and answer ☺️
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! 😊
I am glad it was so helpful.
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.
Awesome!
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!
Explains exactly what i need for a current issue. Thank you Tim. By the way i loved your Web deb masterclass 👍
Thanks for sharing!
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! 🙏
Great job practicing what you are learning.
Finally someone explained it Thank you 👍
You are welcome.
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 :)
Great!
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!
Thanks Tim for this excellent video.
You are welcome.
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.
It has been a while, but I believe we actually wanted them to be instantiated once per call.
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."
Thanks!
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
Fantastic explanations!
Thank you!
WOW! this is wonderful tutorial. 🙏🙏🙏
Thanks!
Great, your awesome my friend, this type of concept works better in big application!
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.
@@IAmTimCorey thanks for taking your time and respond
Omg I’ve been waiting for exactly this! Thanks for what you do 🙏
You are welcome.
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"
If I had a Nickle for every time I hear that...
@@seandavidson see what you did there.
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.
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.
@@codefoxtrot I think this is an important reason of using factory
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.
AbstractFactory name is confusing to me. My intuition was: Abstract = do not instantiate. For me better name is GenericFactory.
Great video - as usual :)
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.
Great Video, Design Patterns are interesting ....👍👍
Thank you!
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.
I'm at a conference right now, but I am working on a fix that should be out soon.
I really love your videos but this one is FANTASTIC. Thank you to explain how to proper implement a factory. =]
You're very welcome!
Thx Tim. Great video. i have a question... why Singleton?
For the factory? Because we don't need multiple instances of it when one will do.
I appreciate this video very much. Do you have one with WPF core that injects a UserControl - where the UserControl has a dependency?
I don't believe so. Not yet.
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
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)?
a registry or static guid's
Hey Tim, when talking about factory pattern we usually mean it as abstract factory pattern or factory method pattern?
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
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 !
Worth using a good DI package like autofac to offload this work where possible.
It can be, if you need those features.
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?
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).
@@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
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.
Great! Are you going to be covering more such things? Thank you for this!
I cover most C# topics, so probably.
@@IAmTimCorey really appreciate series of videos you post. Thank you. Much love from India.
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.
Thanks!
You are welcome.
Can someone explain the right implementation of the last example?
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.
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.
@@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.
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.
Hmmm, not sure in that scenario.
Thankyou.
You are welcome.
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.
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.
Love the video! And how about a factory with an async Create, is that possible?
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().
This is literally hurting my brain. but I won't give up easily.
Stick with it. If you practice it, sometimes that helps it click.
Isnt Func a lambda expression? a function with no name?
But delegates we declare a name then late define it of that delegate type?
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.
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.
That's why I included more of the video - you can do more with the factory than just create multiple instances of a class.
@@IAmTimCorey I'm glad you did, it helps a lot.
DI Container already do factory stuff , constructor injection is working in container's factories
why create other factory outside of container ?
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.
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.
Is this similar to a repository pattern and do you use a respitory pattern?
No, the factory pattern is different than the repository pattern.
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.
Hi Tim, if you have a code behind approach can you navigate me to the url on RUclips please. Again, amazing content
I'm not sure what you mean.
Will you do all patterns? Mostly interested in Builder
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/
@@IAmTimCorey I will. Hopefully it was already on your mind :). I would pay for a complete patterns course.
Tim you're being New()phobic ! 😂😂😂
Absolutely.
???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?
There is a lot to thread safety but it sounds like you are well on your way to that.
How to create instances of the same implementation with different appsettings configuration values? Is a factory the correct solution for this problem?
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.
@@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!
Are you part of the C# language team? They have a Tim there, if I recall correctly. Is it you?
Nope. I don’t work for Microsoft. I own my own business.
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.
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.
@@IAmTimCorey Thank you very much. Have a good day.
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;
You would need to provide those values to the factory and the factory would need to instantiate it with those values.
@@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
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.
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.
@@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?
Why? How does it add additional value?
@@IAmTimCorey in this example it doesn't but if new Car() needed more setup then maybe the extra layer would be good
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.
I do not understand what "English conversation" means. My courses are not also books, though.
As a person with English far from perfect I remembered funny scene fron Pulp Fiction 😂”English motherducker! Can you speak it!?”
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?
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.
@@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.
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.
For TImplementation, isn't 'class' redundant since TInterface is already restricted to class?
Yes, it is.
@@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.
Ah, good catch. This is more of a compile-time issue rather than a "real" issue.
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?
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.
@@codefoxtrot hey, thanks for the reply. Can you please show me an example code?
@@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!
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?
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.
@@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?
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?
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.
@@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!
❤️
😀
That's good, can you please make some deep dive vids on block chain?
Sorry, no. I don't cover blockchain.
Why is it called abstract factory? My thinkng is that generic factory would be a better name
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/
30 mins in to the video, and I dont get it, Usually I never felt this much confused
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.
not suitable for .net8 :-(
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.
@@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
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.
your videos are just too lengthy.. perhaps extremely lengthy.. in this time sensitive world.. please plan it smarter.
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.
Nice try, nice try to pronounce Blazor, LoL
Huh?
Hey, instead of using as x=> () =>x.GetService()! possibly you can use x=>x.GetServices --- without paranthesis.
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?
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.
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
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 )
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));
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.