IOC issue: Too many Abstract Factories for Runtime data dependent classes - dependency-injection

I have recently started to use DI in one of my projects. For runtime dependent classes, I created corresponding Abstract factories. After following this pattern I end up having too many abstract factories, almost one for each of my class.
Is it common to end up having too many abstract factories when using IOC ?
Scenario: Suppose I get an "Entity" object from a database. There are 10 different use cases a user could perform on this entity object. For each of the usecase I have a different class to handle it. In some cases a given use case could have sub use case components which may also need the entity object.
As these classes are dependent on runtime entity object, I had to create abstract factory for each one of them. Finally I wire the construction instructions in the IOC container.
Is there an alternative way of doing it. I just feel creating all these factories is waste of time, ESPECIALLY when all the sub classes are dependent on the same entity object.
I am inclined on having a single factory / builder class registered for my scenario with IOC container. This factory would create the required object graph for my scenario. I see IOC as a tool to help implement DI concept. Not using IOC container all the way may not be bad as long as I am observing DI via a custom builder / factory.
I wanted to know what do you guys think about this approach?

It sounds like you are suffering from an overabundance of 1:1 interfaces. When that happens it's often a sign that one should stop and think about the Reused Abstractions Principle.
Perhaps you can redesign your interfaces so that there are less factories and more commands.

Related

Dependency injection and object creation

When I use dependency injection, I create all objects at the very beginning of the program.
I end up having to carry dependencies through a lot of constructors, although it would be more easy to create them somewhere earlier.
The pattern of factories comes to mind. Factory can be passed in the constructor to not violate DI.
But isn't this an anti-pattern / violating of DI? Since Factory creates a concrete implementation of the object?
What are the approaches to create objects without breaking DI?
When practicing DI, there is no need or requirement to construct all objects at startup; that's a design choice or perhaps a design constraint in your particular environment. In fact, lazy initialization with DI is the norm—not the exception.
But the consequence of lazy initialization of object graphs is that you typically have some factory-like behavior somewhere in the application.
Many application types, like web application frameworks, provide a factory abstraction that you can implement or override that allows you to create the necessary objects for the request that comes in.
If you do this, and create the object structure specific for a request, just in time when a request comes in, I'd say that in most cases there is no need for postponing the creation of other objects for that request. This means there's no need for injecting any factory classes into the classes of your application. I'd say that in most cases, Abstract Factories are a Design Smell.
But there are exceptions, though, and the argument that Abstract Factories should be reviewed with suspicion, doesn't mean that you don't need factory-like behavior somewhere inside your code. Whenever you're doing message dispatching, for instance, where an incoming message gets dispatched to one or multiple handlers, where many handler classes exist in the application, requires lazy initialization of classes, and requires factory-like behavior. This, however, can be hidden behind abstractions that are implemented inside the Composition Root, which prevents application code from depending on an Abstract Factory.
But that said, not all application frameworks expose factory abstractions for you to implement, and as I said, there are always exceptions to the rule.

Using factories to create multiple objects when using Dependency Injection

I am trying to figure out how to create multiple objects when using Dependency Injection. As far as I understand the standard approach is to inject a Factory which is then used to create the objects. The part I struggle with is how the Factory creates the objects. So far I see two possible solutions:
The Factory just uses new() to create the object.
Isn't DI supposed to free me of the use of new for non value objects?
What happens if the Object to be created has dependencies that could be resolved by the IoC?
Use the Container as Serviclocator
solves the problems of just newing objects at the cost of introducing an antipattern or is it no longer an antipattern if the use of the serviclocater is constraind within the factories?
It feels like i can coose between a bad and a bad solution. Is there something I am missing or do I understand somthing wrong here?
Edit Currently I am not using an Ioc at all but thinking about Ninject. Although the Autofac DelegateFactories sound very promising.
For starters, I don't consider using a container as service locator in factories an anti-pattern. There are genuine circumstances where it is entirely appropriate. Come to think about it, container aware factories are really container extensions, and those seem to be excluded from service locator bashing. Even the most pure IoC frameworks like AutoFac or Ninject have extensive extension capabilities. A most typical use case for this pattern is resolving to different implementations based on where the service is used.
With regards to using new to create instances inside factories, that is acceptable as well. The IoC/DI message got a bit distorted there and never using new is really a side effect, rather than the goal of DI. The first imperative of Dependency Injection is to externalise creation of dependencies from the component. A factory satisfies that imperative as long as it itself gets injected into component. The questions you need to ask yourself when evaluating such scenarios are:
Does the component itself create its dependencies? A: No, the factory does.
Can you make the component work with different dependencies without modifying it? A: Yes, by injecting a different factory.
I said this before, IoC containers are just factories on steroids. For 80% use case they work out of the box. The other 20% might require tweaks of the above two varieties. I tend to use container aware factories when I want to create components that require both registered dependencies and some input at run-time and new-ing factories when I create Domain objects that don't have dependencies on other services, but take all their construction parameters at run time.
Although the interface for your factory will be defined at the application level, you would typically define the implementation of that factory class close to your DI configuration, thus as part of your composition root. Although calling the container directly from your code is an implementation of the Service Locator anti-pattern, any code that is defined inside the compostion root is merely mechanics and is therefore not Service Locator. As long as newing up objects or calling into the container is done inside (or very close to) the composition root, this is not a problem, because the application will still be clean from any locator / container.
In other words: use the factory approach. Whether or not you need to new up objects directly inside your factory or make use of the container, depends on the objects. Letting the container create the objects is preferable, especially when they got dependencies on their own, but not all objects can be created by the container. In that case you need to revert to the new operation. Both are fine when the code is part of the composition root and not of the application. The factory itself can have dependencies of its own. This should not be a problem. You can let the container wire-up the factory instance.

Usage patterns/use cases for DI or when to start using it

I'm not sure for which use cases one should to use DI in the application. I know that injecting services like PlaceService or CalculationService etc fits very well but should I also create my domain objects with DI like a User? What is if the User has only one constructor which requires a first and lastname. Is this solveable with DI?
Should I use DI to create the instances for Set/List interfaces or is this pure overkill?
I use guice primarily.
The answer by ig0774 is a good starting point. In addition, I would like to offer this rule of thumb:
In the terminology of Domain-Driven Design, you should DI for services, but not for entities or value objects.
In other words, DI fits well with conceptually long-lived, stateless objects of which there are usually one or a known number in use.
The rule I use is, in general, to favor dependency injection, except where the object can be constructed with purely primitive values and there is no / a minimal chance that the object might be replaced by another implementation.
However, for domain objects, particularly if your objects do not constitute an anemic domain model, i.e., where objects are just bags of getters and setters, it can be useful to have objects that, for example, can persist themselves to a datastore, etc. For those sort of objects, dependency injection and Salve can be a powerful combination.
Guice has a specific solution to the type of problem posed by objects like your User object called AssistedInject, though similar things are also possible with other lightweight containers or using something the builder or adapter patterns.

Why does any kind of abstraction use interfaces instead of abstract classes?

Heyho,
There´s a question in my mind for some time now, which hopefully can be cleared quickly by some of you:
I am a big fan of MVC, ASP.Net Mvc in my case.
What I have noticed is the hype about interfaces. Every video, tutorial and book seems to solve any kind of abstraction with interfaces. I have adapted these patterns, understood why and how and I am basically very happy with it.
But I just don´t get why interfaces are used everywhere. I´ve almost never seen some abstraction being done with abstract base classes, which I don´t understand. Maybe I miss something? I know that you can only inherit from one base class while multiple interfaces are possible. But interfaces do have disadvantages, especially when some changes need to be done, which breaks your implementations.
In my projects so far, I only used to pick interfaces for completely different classes.
For example, the whole repository pattern could be done with an abstract base class, still providing testability and exchangeability, or did I miss something?
Please point me to the part where my brain laggs :)
Interfaces are used in tutorials, blogs and elsewhere because those authors are particularly influenced by a group of methodology called "design for testability".
Primarily, design for testability school of thoughts used interface every way because they want to be able to mock any component under tests. If you use concrete class, then a lot of mocking tools can't mock those class, and hence will make it difficult to test your code.
A Story
I once attended a Java user group
meeting where James Gosling (Java's
inventor) was the featured speaker.
During the memorable Q&A session,
someone asked him: "If you could do
Java over again, what would you
change?" "I'd leave out classes," he
replied. After the laughter died down,
he explained that the real problem
wasn't classes per se, but rather
implementation inheritance (the
extends relationship). Interface
inheritance (the implements
relationship) is preferable. You
should avoid implementation
inheritance whenever possible.
While using only or mostly Interfaces does have code reuse problems(as well as eliminating nice base classes), It makes it a lot easier to do Multiple Inheritance like things. As well as having widely different implementations that will work and where you don't have to worry about the base class changing or even what it does(you do have to implement the whole thing though so its a trade off).
P.S. I think the new Go language is based on interfaces rather then inheritance(looks sort of interesting).
If the language doesn't support multiple inheritance or mix-ins abstract base classes are limited in scope compared to interfaces. E.g. in .NET if you must inherit from some other type such as MarshalByRef, you can't use an abstract base class to implement a pattern. Interfaces do not impose this restriction.
Besides the fact you mentioned that you can inherit from a single base class only (which is pretty inconvenient if you want to use an existing class that already inherits from some class with the new framework base class), you also avoid the fragile base class problem if you use interfaces instead.
Coding against interfaces makes your design more flexible and extensible. For instance, plugin frameworks and dependency injection. Without interfaces, the extensibility of it is pretty much limited.
Read about interfaces, abstract classes, breaking changes, and MVC here: http://ayende.com/Blog/archive/2008/02/21/Re-Versioning-Issues-With-Abstract-Base-Classes-and-Interfaces.aspx.
One solution that is presented there (or somewhere else on Ayende's blog) is: do use interface but also provide abstract classes. Those who case about breaking changes can base their implementations on abstract classes. Those who need power of interfaces are also satisfied. But do make sure your methods accept interfaces, not abstract classes, as input.

When to use Dependency Injection

I've had a certain feeling these last couple of days that dependency-injection should really be called "I can't make up my mind"-pattern. I know this might sound silly, but really it's about the reasoning behind why I should use Dependency Injection (DI). Often it is said that I should use DI, to achieve a higher level of loose-coupling, and I get that part. But really... how often do I change my database, once my choice has fallen on MS SQL or MySQL .. Very rarely right?
Does anyone have some very compelling reasons why DI is the way to go?
Two words, unit testing.
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up 'test' data.
DI is very useful for decoupling your system. If all you're using it for is to decouple the database implementation from the rest of your application, then either your application is pretty simple or you need to do a lot more analysis on the problem domain and discover what components within your problem domain are the most likely to change and the components within your system that have a large amount of coupling.
DI is most useful when you're aiming for code reuse, versatility and robustness to changes in your problem domain.
How relevant it is to your project depends upon the expected lifespan of your code. Depending on the type of work you're doing zero reuse from one project to the next for the majority of code you're writing might actually be quite acceptable.
An example for use the use of DI is in creating an application that can be deployed for several clients using DI to inject customisations for the client, which could also be described as the GOF Strategy pattern. Many of the GOF patterns can be facilitated with the use of a DI framework.
DI is more relevant to Enterprise application development in which you have a large amount of code, complicated business requirements and an expectation (or hope) that the system will be maintained for many years or decades.
Even if you don't change the structure of your program during development phases you will find out you need to access several subsystems from different parts of your program. With DI each of your classes just needs to ask for services and you're free of having to provide all the wiring manually.
This really helps me on concentrating on the interaction of things in the software design and not on "who needs to carry what around because someone else needs it later".
Additionally it also just saves a LOT of work writing boilerplate code. Do I need a singleton? I just configure a class to be one. Can I test with such a "singleton"? Yes, I still can (since I just CONFIGURED it to exist only once, but the test can instantiate an alternative implementation).
But, by the way before I was using DI I didn't really understand its worth, but trying it was a real eye-opener to me: My designs are a lot more object-oriented as they have been before.
By the way, with the current application I DON'T unit-test (bad, bad me) but I STILL couldn't live with DI anymore. It is so much easier moving things around and keeping classes small and simple.
While I semi-agree with you with the DB example, one of the large things that I found helpful to use DI is to help me test the layer I build on top of the database.
Here's an example...
You have your database.
You have your code that accesses the database and returns objects
You have business domain objects that take the previous item's objects and do some logic with them.
If you merge the data access with your business domain logic, your domain objects can become difficult to test. DI allows you to inject your own data access objects into your domain so that you don't depend on the database for testing or possibly demonstrations (ran a demo where some data was pulled in from xml instead of a database).
Abstracting 3rd party components and frameworks like this would also help you.
Aside from the testing example, there's a few places where DI can be used through a Design by Contract approach. You may find it appropriate to create a processing engine of sorts that calls methods of the objects you're injecting into it. While it may not truly "process it" it runs the methods that have different implementation in each object you provide.
I saw an example of this where the every business domain object had a "Save" function that the was called after it was injected into the processor. The processor modified the component with configuration information and Save handled the object's primary state. In essence, DI supplemented the polymorphic method implementation of the objects that conformed to the Interface.
Dependency Injection gives you the ability to test specific units of code in isolation.
Say I have a class Foo for example that takes an instance of a class Bar in its constructor. One of the methods on Foo might check that a Property value of Bar is one which allows some other processing of Bar to take place.
public class Foo
{
private Bar _bar;
public Foo(Bar bar)
{
_bar = bar;
}
public bool IsPropertyOfBarValid()
{
return _bar.SomeProperty == PropertyEnum.ValidProperty;
}
}
Now let's say that Bar is instantiated and it's Properties are set to data from some datasource in it's constructor. How might I go about testing the IsPropertyOfBarValid() method of Foo (ignoring the fact that this is an incredibly simple example)? Well, Foo is dependent on the instance of Bar passed in to the constructor, which in turn is dependent on the data from the datasource that it's properties are set to. What we would like to do is have some way of isolating Foo from the resources it depends upon so that we can test it in isolation
This is where Dependency Injection comes in. What we want is to have some way of faking an instance of Bar passed to Foo such that we can control the properties set on this fake Bar and achieve what we set out to do, test that the implementation of IsPropertyOfBarValid() does what we expect it to do, i.e. return true when Bar.SomeProperty == PropertyEnum.ValidProperty and false for any other value.
There are two types of fake object, Mocks and Stubs. Stubs provide input for the application under test so that the test can be performed on something else. Mocks on the other hand provide input to the test to decide on pass\fail.
Martin Fowler has a great article on the difference between Mocks and Stubs
I think that DI is worth using when you have many services/components whose implementations must be selected at runtime based on external configuration. (Note that such configuration can take the form of an XML file or a combination of code annotations and separate classes; choose what is more convenient.)
Otherwise, I would simply use a ServiceLocator, which is much "lighter" and easier to understand than a whole DI framework.
For unit testing, I prefer to use a mocking API that can mock objects on demand, instead of requiring them to be "injected" into the tested unit from a test. For Java, one such library is my own, JMockit.
Aside from loose coupling, testing of any type is achieved with much greater ease thanks to DI. You can put replace an existing dependency of a class under test with a mock, a dummy or even another version. If a class is created with its dependencies directly instantiated it can often be difficult or even impossible to "stub" them out if required.
I just understood tonight.
For me, dependancy injection is a method for instantiate objects which require a lot of parameters to work in a specific context.
When should you use dependancy injection?
You can use dependancy injection if you instanciate in a static way an object. For example, if you use a class which can convert objects into XML file or JSON file and if you need only the XML file. You will have to instanciate the object and configure a lot of thing if you don't use dependancy injection.
When should you not use depandancy injection?
If an object is instanciated with request parameters (after a submission form), you should not use depandancy injection because the object is not instanciated in a static way.

Resources