Is default scoped binding preferred to Singleton binding for stateless objects? - dependency-injection

According to the Guice wiki page, unscoped binding is preferred to Singleton for stateless objects.
I do not agree with the statement though because:
Singleton scope gives more information to developers. Developer can assume singleton objects are thread-safe and they can be injected without using Provider most of the time.
Creating an unscoped object can be expensive because of dependencies to other unscoped objects.
Cyclic dependency of unscoped objects can only be resolved with Providers, which could lead to weird behavior.
e.g. A depends on B, B depends on Provider, and some method f() in A invokes B which invokes some method in A, then a new instance of A and B will be created each time f() is called.
When injecting a Request Scoped object into unscoped objects, it is hard to tell if you need a provider or not because the life cycle of unscoped object is unknown.
Could someone explain why is default scoped preferred to singleton scope for stateless objects?

There's one big and important reason for the preference to unscoped objects instead of singleton objects: Singleton objects can never be garbage collected, nor can the entire transitive tree of objects to which they hold references. Their construction needs to be synchronized (to prevent race conditions during creation), and then they remain in memory for the entire lifetime of the Injector.
This is particularly an issue because, in a production environment, all Guice singletons are eager regardless of whether they're bound asEagerSingleton. This means that in production your memory commitment of your singleton tree starts when the Injector is created, and often lasts until the application closes.
Using Singletons for everything may cause slower startup and larger memory requirements than judiciously choosing singletons.
Of course, if the object and its dependencies are all stateless, the memory footprint of each object is pretty light. However, if your singleton depends on an object that depends on an object that depends on a database, then that database and its memory will be required on startup and never freed.
injector ___________________TIME_________________________\
creation /
|---------------------SINGLETON-------------------------->
|----------REQUEST A------------| |---REQUEST B----->
|-UNSCOPED C-| |-UNSCOPED D-| |-UNSCOPED E-|
Scopes track roughly to the lifetime of the object, and the goal is to avoid injecting a narrower-scoped object into a wider-scoped object (say, keeping around unscoped object C, which might be relevant to request A but not request B). To do so would be a scope-widening injection.
When you refer to unscoped objects, think of them as ephemeral or disposable, and having the narrowest scope possible. This makes it particularly easy to make stateless objects unscoped, because it doesn't matter which instance you have.
Those unscoped objects are also free to inject any object in the graph without using providers, on the assumption that the unscoped object will always have the shorter lifetime compared to any other dependency you pick. By contrast, a singleton must use providers for all of its non-singleton dependencies, because it will absolutely outlive any non-singleton it depends on.
This should make it clear when you need Providers, as you allude to in #1 and #4 above.
In summary, I can only direct you back to the section you linked: Unless you have a good reason (state, expensive construction, or resource management) you should probably leave your injectors unscoped.

Related

Object lifecycle management and IoC containers

I'm updating a game from single player to multiplayer. In this case the game was originally written with most classes being single instanced. e.g. there was a single Player object, a single GameState object, etc. That is, each of these objects lived as long as the application.
Now that more than one player can play at once I obviously need to support creating more than one Player object, GameState object, etc. Over the course of working on this I have come to realize that most objects have one of three lifespans:
App's lifespan, e.g. a Conductor to handle navigation
Player's lifespan, e.g. the SettingsViewModel for the current player
Game's lifespan, e.g. the GameState for the current game
I'm curious how others deal with the creation of these different objects using an IoC container. I want to avoid creating factory classes for each class with a player or game lifespan.
Here is an example of IOC that may help. The project is called IOC-with-Ninject. It uses Ninject plus an IOC container class to manage all object life spans. You will need to do a little research on Ninject to customize it to your specific needs, but this is your IOC container solution (IMHO) if you are using .NET and will help you organize your code base. This is a personal choice, but I swear by it. If you are not using .NET it will still give you an easy pattern to follow. Cheers.
Many IoC containers have custom life-cycle scopes which you can manage as your wish. For example in Ninject you can define your custom life cycle scope as follows:
kernel.Bind<IService>().To<Service>().InScope((c, o) => yourCustomeScope);
As long as the yourCustomeScope variable has not changed, one single instance of the Service object is returned each time the kernel receives a request for IService. As soon as the yourCustomeScope variable changes, a new instance of Service will be created on the next request for IService. yourCustomeScope can be the current player instance, the game object or anything that you want to change the lifetime of the Service object, based on its reference change.
However, the objects that you just mentioned are more likely to be entities rather than services for which I don't think injection is a good idea.
From my experience the factories approach works the best.
Controlling lifespan of instance is clunky for support and requires efforts, knowledge of all of the classes lifespan requirements and dependencies, time for configuration and management of the configuration. In same time the use of factories is natural and code specific.
Factories (implementation) creation might be avoided by using proxy factories . You can also have factories returning generic arguments to further decrease the needs of factories (interfaces) creation.
If still too many factories are required I suggest reviewing the code flow.
I think this is in part a rehash of some of the comments of the previous answers but I have tried to exemplify expand a little on some of the reasoning.
Once you get into the domain of managing injected objects lifespan, you probably should be creating factories for these objects.
The underlying problem is that the composition root is not aware of what the environmental context of the call will be that needs to create the object.
I think I should take a step back and explain at this point.
Received wisdom on dependancy injection is to have a composition root some where near the entry point of the code. There are many good reasons for this that are not difficult to find on the web so I won't go into that here.
The composition root is where you map your interfaces (usually, but possibly objects) to their implmentations. You can pass in information that is available at this point to the constructor. So you can pass in a reference to an object whose lifetime is current at the time of execution of the composition root.
However, if the lifetime of the composition root does not overlap with the life time of the object you want to create you have to defer the execution of the constructor until the object needs to be created. This is why you need to have a factory. You can pass a factory method in to your mapping at this point and thus pass in the information needed to generate the object, but allow the creation to happen at the time it is required not when the composition root is executed.
You do not need a factory class to do this factory methods are fine, moreover the factory method can be inlined and so the code overhead is not much more than if we were creating the objects in the composition route.
If we have a project with 2 services where the first service is dependant on the first and we only want the lifetime of the second service to start when we create the first service we might have something like the following. (I am using ninject to give a code example, but I expect that other IOC containers work similarly in this respect.)
`
public class Service1:IService
{
private Func<IService>serviceFactoryMethod _Service2Factory;
public Service1(Func<IService>service2FactoryMethod)
{
_Service2Factory=service2FactoryMethod;
}
public void DoSomethingUsingService2()
{
var service2=_Service2Factory();
service2.DoSomething();
}
}
public class MainClass
{
public void CompositionRoot()
{
var kernel= new StandardKernel();
kernel.Bind.ToMethod(m=>
{
return new Service1(m.Kernel.Get<IService2>());
}
}
}
`
This example does not address how you would manage the lifetime of the App, players and games lifespans, but hopefully it gives sufficient clues as to how to remove lifetime issues related to dependancy injection.
Side note: that using Ninject you would be able to change the scope of Service2 in order to manage its lifetime to go beoynd the lifetime of Service1. For example, if you knew each instance of a game were to happen on its own thread (OK, this maybe somewhat unlikely), you might use InThreadScope for the game.

Are these values dependencies?

I've got an object that encapsulates remote calls. It needs credentials to make the calls. I think the credentials should be passed into the constructor so that, once the object is created, a user doesn't have to keep passing them in every time they make a call to the object. This seems like a sensible factoring.
If I do this though I've got the added complexity of the clients that use this object needing to be passed a factory instead of the object itself because they credentials won't be known until run time. So given this extra work, I was wondering if credentials (being just string values and no code) count as a dependency or not?
Does this question even make sense? You see I've gotten it into my head after using IoC that anything being passed into a constructor counts as a dependency and thus should probably be an instance of some implementation of an interface.
I wouldn't see those strings as dependencies. Instead, create an IUserContext or IUserCredentials abstraction that you can inject.

Why not use an IoC container to resolve dependencies for entities/business objects?

I understand the concept behind DI, but I'm just learning what different IoC containers can do. It seems that most people advocate using IoC containers to wire up stateless services, but what about using them for stateful objects like entities?
Whether it's right or wrong, I normally stuff my entities with behavior, even if that behavior requires an outside class. Example:
public class Order : IOrder
{
private string _ShipAddress;
private IShipQuoter _ShipQuoter;
public Order(IOrderData OrderData, IShipQuoter ShipQuoter)
{
// OrderData comes from a repository and has the data needed
// to construct order
_ShipAddress = OrderData.ShipAddress; // etc.
_ShipQuoter = ShipQuoter;
}
private decimal GetShippingRate()
{
return _ShipQuoter.GetRate(this);
}
}
As you can see, the dependencies are Constructor Injected. Now for a couple of questions.
Is it considered bad practice to have your entities depend on outside classes such as the ShipQuoter? Eliminating these dependencies seems to lead me towards an anemic domain, if I understand the definition correctly.
Is it bad practice to use an IoC container to resolve these dependencies and construct an entity when needed? Is it possible to do this?
Thanks for any insight.
The first question is the most difficult to answer. Is it bad practice to have Entities depend on outside classes? It's certainly not the most common thing to do.
If, for example, you inject a Repository into your Entities you effectively have an implementation of the Active Record pattern. Some people like this pattern for the convenience it provides, while others (like me) consider it a code smell or anti-pattern because it violates the Single Responsibility Principle (SRP).
You could argue that injecting other dependencies into Entities would pull you in the same direction (away from SRP). On the other hand you are certainly correct that if you don't do this, the pull is towards an Anemic Domain Model.
I struggled with all of this for a long time until I came across Greg Young's (abandonded) paper on DDDD where he explains why the stereotypical n-tier/n-layer architecture will always be CRUDy (and thus rather anemic).
Moving our focus to modeling Domain objects as Commands and Events instead of Nouns seems to enable us to build a proper object-oriented domain model.
The second question is easier to answer. You can always use an Abstract Factory to create instances at run-time. With Castle Windsor you can even use the Typed Factory Facility, relieving you of the burden of implementing the factories manually.
I know this is an old post but wanted to add. The domain entity should not persist itself even if you pass in an abstracted repository in ctor. The reason I am suggestion this is not merely that it violates SRP, it also contrary to DDD's aggregation. Let me explain, DDD is suited for complex apps with inherently deep graphs, therefore, we use aggregate or composite roots to persist changes to the underlying "children", so when we inject persistence into the individual children we violate the relationship children have to the composite or aggregate root that should be "in charge" of the life cycle or aggregation. Of course the composite root or aggregate does not persist it's own graph either. Another is with injecting dependencies of DDD objects is that an injected domain object effectively has no state until some other event takes place to hydrate its state. ANy consumer of the code will be forced to init or setup the domain object first before they can invoke business behavior which violates encapsulation.

IoC Dependency Injection for stateful objects (not global)

I'm new to this IoC and DI business- I feel like I get the concept if you are passing along objects that are of a global scope, but I don't get how it works when you need to pass around an object that is of a specific logical state. So, for instance, if I wanted to inject a person object into a write file command object- how would I be able to choose the correct person object dynamically? From what I have seen, I could default construct the object, but my disconnect is that you wouldn't use a default person object, it would need to be dynamic. I assume that the IoC container may just maintain the state of the object for you as it gets passed around, but then that assuems you are dealing in only one person object because there would be no thread safety, right? I know I am missing something, (maybe something like a factoryclass), but I need a little more information about how that would work.
Well, you can always inject an Abstract Factory into your consumer and use it to create the locally scoped objects.
This is sometimes necessary. See these examples:
MVC, DI (dependency injection) and creating Model instance from Controller
Is there a pattern for initializing objects created via a DI container
Can't combine Factory / DI
However, in general we tend to not use DI for Entities, but mostly for Services. Instead, Entities are usually created through some sort of Repository.
When you construct an service object (e.g. WriteFileService), you inject into it things it needs internally to complete it's job. Perhaps it needs a filesystem object or something.
The Person object in your example should be passed to the service object as a parameter to a method call. e.g. writeFileService.write(person)

Inversion of control domain objects construction problem

As I understand IoC-container is helpful in creation of application-level objects like services and factories. But domain-level objects should be created manually.
Spring's manual tells us: "Typically one does not configure fine-grained domain objects in the container, because it is usually the responsibility of DAOs and business logic to create/load domain objects."
Well. But what if my domain "fine-grained" object depends on some application-level object.
For example I have an UserViewer(User user, UserConstants constants) class.
There user is domain object which cannot be injected, but UserViewer also needs UserConstants which is high-level object injected by IoC-container.
I want to inject UserConstants from the IoC-container, but I also need a transient runtime parameter User here.
What is wrong with the design?
Thanks in advance!
UPDATE
It seems I was not precise enough with my question. What I really need is an example how to do this:
create instance of class UserViewer(User user, UserService service), where user is passed as the parameter and service is injected from IoC.
If I inject UserViewer viewer then how do I pass user to it?
If I create UserViewer viewer manually then how do I pass service to it?
there's nothing wrong with this design. you use Factories for that, which have one leg in the domain, one leg in infrastructure.
You can either write them manually, or have the container do that for you, by things like TypedFactoryFacility in Windsor.
Also when your domain objects come from persistence layer you can plug your container there to inject the services they require (NHibernate can do that).
But what if my domain "fine-grained" object depends on some application-level object?
It is precisely this that is considered bad-practice. I would say the problems could be:
There are tons of these objects, so there can be performance and memory issues.
The POJO style is that they can be used in all environments (persisted in the database, processed in business algorithms and rules, read and set in view technologies, serialized and send over the network). Injecting application-level objects in them could cause the following problems:
In your architecture, you probably have the rule that some (most) application-level objects are usable in some layers, not in others. Because all layers have access to the pojos, the rule would be violated transitively.
When serialized and rebuild in another JVM, what would be the meaning of your application-level objects. They are useless, they must be changed for the local equivalents...
Typically, the pojos that constitute your domain are self-contained. They can have access to other pojos (and many enums), that's all.
In addition to the data, they have methods that implement the details of the business rules or algorithms (remember the OO idea of grouping data and code that work on it ;-) ):
This is especially good when they have inheritance, as this allow to customize a business rule for some pojo by providing a different implementation (differing case without if or switch: remember OO? ;-) ).
Any code that requires access to application-level objects (like accessing the database) is taken out, for example to a Service or Manager. But that code stays high level, thus readable and simple, because the pojos themselves take care of the low level details (and the special cases).
After the fact, you often find out that the pojo methods get reused a lot, and composed in different ways by the Services or Managers. That's a big win on reducing duplication, the methods names provide much needed "meaning", and provide an easier access to developers that are new to a module.
For your update:
create instance of class UserViewer(User user, UserService service), where user is passed as the parameter and service is injected from IoC.
If I inject UserViewer viewer then how do I pass user to it?
If I create UserViewer viewer manually then how do I pass service to it?
In that case, you need a factory method (possibly on a Factory or Locator of yours). It could look at follow, separating the two parts:
public UserViewer createUserViewer(User user) {
UserViewer viewer = instantiateBean(UserViewer.class);
viewer.setUser(user);
return viewer;
}
private <E> E instantiateBean(Class<E> clazz) {
// call the IoC container to create and inject a bean
}

Resources