.Net Diference between Factory and Container? [closed] - c#

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have never used a ioc-Container but from what I have read, the objects suffixed with "Container" seem to me a factory that reads from configuration/context, does its magic and returns an object of concrete type according to the read configuration/context.
What key aspects am I missing?
Using containers seems to add complexity (which is time consuming for development, refactoring and configuration), where to use and which are the key benefits?

Both IoC containers and factories build other objects, but that's where the similarities end.
A factory is an object which knows how to build other objects. It encapsulates extra logic, perhaps configuration time information etc. It can build several of a related type of objects, such as from a hierarchy of objects. But the number of objects it can build is part of the structure of the factory. So you might have a SqlConnectionFactory or a RequestHandlerFactory, which know what sort of SqlConnections or RequestHandlers to build, but if you want to build InputValidators you're going to need to make a new factory.
An IoC container is a tool used to help with the inversion of control pattern. But it's not strictly needed. IoC makes you be explicit in what dependencies your objects have, and makes you provide those dependencies when the object is created/initialized. When done right, this helps with separation of concerns, decoupling between components, unit testing etc. and generally makes the resulting code "better". But because manually wiring up object graphs is a hassle, a number of frameworks for doing this automatically, either from external configuration or from code annotations have appeared. These are called IoC containers. The way they initialize objects is much more generic than a factory. You can ask it to build any type of object, and as long as it knows something about those objects (the signature of the constructor, in the simplest case), it can build them.
It's more usual to see an IoC container use a factory, than the other way around. In much of the code I've seen, the need for factories for all but the most complex objects is greatly alleviated though.

Related

Unit test , large setups/fixtures [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Lets say we have a Service with other servcies on DI. The method under test does somehting with the input data, does some validations, calls a couple of these injected services (can get data only or modify data and then return something) and then returns something.
Given this scenario, I need to write many cases testing all possible behaviors, like validations exceptions, not found exceptions, business exceptions, normal flow, etc...
The problem is that I need to mock all the methods on an injected service for the setup. This could grow fast.
What's the best approach for fixtures and setups (mocking dependencies) in this large/complex method? Is there a pattern that solves this?
For data mocking I use builder pattern wich simplifies the task very well.
You should try create independent classes, which you could test without introducing too many dependencies, but in some point there will be a class which uses other components(for example ViewModel). In such cases I use:
https://github.com/AutoFixture/AutoFixture
It helps in creation system/class under test and helps with injecting dependencies. You can use it with NSubstitute but not only with it.
Using AutoFixture you can create mock classes which you will examine, but rest dependencies which will be not needed AutoFixture will auto-generate for you, so extending a constructor will not lead to modifying bunch of unit tests.

Injection or creating instance with new() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm a C# programmer and I'm thinking about dependency injection. I've read "Dependency injection in .NET" book and patterns and antipatterns of DI are quite clear for me. I use pattern injection in constructor most of the time. Are there any cases in wich it is preferrable to create instances directly rather than using a Dependency Injection framework?
Using Dependency Injection has the advantage of making code Testable, however abusing DI pattern makes code harder to understand. Take in example this framework (ouzel, I'm not affiliated in any way. I just liked the way it was designed) wich I started recently to follow, as you see most classes have dependencies injected, however there is still a single instance shared without constructor injection sharedEngine.
In that particular case I find the author did a good choice, that makes the code overall simpler to understand (simpler constructors, less members) and eventually more performant (you don't have a shared pointer stored in every instance of every class of the engine).
Still its code can be tested because you can replace that instance (global) with a mock (the worst point of globals is that initialization order and their dependencies are hard to track, however if you limit to few globals with no or few dependencies this is not a problem). As you see you are not always forced to inject everything from constructor (and I wrote a DI injection framework for C++).
The problem is that people think is always good injectin everything from constructor so you suddendly start seeing frameworks that allow to inject everything (like int or std::vector<float>) while in reality that's the worst idea ever (infact in my simple framework I allow just to inject classes) since code becomes harder to understand because you are mixing configuration values with logic configuration and you have to travel through more files to get a grasp of what code is doing.
So, constructor injection is very good, use it when it is proper, but it is not the Jack-of-all-trades like everything in programming you have to not abuse it. Best of all try to understand good examples of every programming practice/pattern and then roll your own recipe, programming is made of choices, and every choice have good and bad sides.
When is it Ok (and by "OK" I mean you will still be able to test the code, as it were not coupled to concrete instances) to call "new":
You need Polymorphis, most times it is easier to create the new class than configuring that using a DI framework
You need a object factory, usually the factory itself is injected, however the factory code call "new" explicitly
You are calling "new" in the main
The object you are creating with "new" has no dependencies, and thus using it inside a class does not make the class harder to test (in example you create standard .NET containers with new, doing otherwise results in much more confusion)
The object you are creating is a global instance wich do not rely on order of initialization and its dependencies are not visible otherelse (you can mock the instance as long as you access it through a interface).
The above list provide situations in wich even when using a DI framework (like Ninject) it is ok to call "new" without removing the possibility to test your code, even better, most times you use DI in the above cases you usually end up with more complex code.

Singleton pattern combined with Factory [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm running an email marketing program that runs and schedules campaigns. So I have two types of campaigns in it:
Ad hoc
Scheduled
And since I want my program to create one campaign at a time. I think I'm going to need Singleton pattern.
Each campaign has attributes that are common and attributes that are specific. E.g. Adhoc campaign does not need a time schedule. Also a scheduled campaign reads from a pre-written SQL file while ad hoc campaigns are run instantly.
I would like to have a well-structured design to support these. Is a combination of Factory and Singleton the answer?
If so, can I have a simplified example?
If not, what do you recommend?
Patterns are nice, but a pattern is a solution to a specific problem. You don't seem to have any of those specific problems.
From your requirements, you need a single variable of a base-type and an if-statement to put either one or another derived class into it.
If you want noodles, you have to decide if it should be spaghetti or tortellini. Pick one, heat, eat. Please don't build a NoodleHeatingAbstractFactory that only allows heating of a single, well guarded noodle dish. Keep it simple.
You typical use singletons when you want a global shared resource. To have one instance of something you don't necessarily need a singleton unless it is created from multiple locations, if not you can just create one instance and pass it around. I think AbstractFactory fits well here, but not sure about Singleton.
Update
If the user chooses which campaign to create I don't think you need a factory. Just create the appropriate campaign and you can store it in a ServiceLocator which is usually a Singleton or alternatively inject it into each Form/Window that you create.
The dependency injection Tends to be a it easier to unit test as you can mock the campaign

in which cases should be used certain types of IoC frameworks [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I know that there are many IoC frameworks in .net ( They are: Ninject, Unity, Castle Windsor , Structure Map ) They also used to same goal - resolving dependencies. But i don't understand in which cases should be used certain framework! they are almost similar. Who can simply explain the main differences?
It depends on your needs. Some containers are very mature or have a big community. Others are feature rich or very fast. It all depends on what you need, but the problem is that you only know this when you already did one or two projects using DI and DI containers. And still, when you're architecture changes the requirements for your container will change.
So whatever container you pick, be prepared to change your container. This means, stick to the Dependency Injection pattern and prevent yourself from letting application code have a direct dependency on the container (a pattern which is called Service Locator).
Each and every one has a fatal flaw.
On a more serious note they surely do essentially the same thing, but differ in implementation details, conventions, performance, auxiliary features and suggested usecases.
I don't think that you should really sweat picking the IoC container. Stick to one you're used to and continue with your core functionality.
DI/IOC or whatever you want to call it is a means to an end - not the end in itself. Find one you like and that does everything you need and go with it (until you're told to use something else).
I rolled my own based on StructureMap and probably learned more doing that than actually using any of the others.

my class has 30 properties, unit testing is a pain no? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My class has like 30-40 properties, and I really want to unit test.
But I have to create a moq instance (many of them, with different combinations etc).
Is there an easy way? This is real work!
My class can't be refactored, "trust me" (hehe, no really it can't, they are just properties of the object that are very tightly coupled).
Sounds like you need to do some major refactoring. I would start by taking a good look at the single responsibility principle, and making classes that will only have 1 reason to change. Once you break out functionality into separate classes that deal with only 1 responsibility, you can start writing tests for those classes, and they shouldn't take a page-full of mock objects.
This is the advantage of test-driven development -- you immediately run into the problems caused by huge classes, and are driven to avoid them if you want to be able to write tests.
Personally, I don't think you need to try every combination to test your class.
You mention lots about properties, but little about behavior. Shouldn't the tests be about behavior more than state?
There could well be situations where, due to the nature of the class, there are a lot of legitimate properties. I know, I've been there and done that. When examining that class, it is important to determine that each property really does belong in the one class, and not elsewhere. Single Responsibility Principle comes in play here.
Unfortunately, to break any tight coupling, it will take some time and effort to refactor. Just suck it up and get 'er done!

Categories