Singleton Vs Singleton Factory - ios

We have a system which has a lot of model objects (e.g. Car, Pedestrian, Road, ...)
Currently all of them have managers (CarManager, PedestrianManager, RoadManager) that return a singleton of the respective class.
An alternative proposed is to have a ManagerFactory singleton that can return instances of CarManager, PedestrianManager, RoadManager. (e.g. ManagerFactory.getInstance().getCarManager())
We also write test for the project and the concern was that if we will use Dependency Injection we will need an actual instance of an object to inject managers.
Is this alternative a good one? Would you change the singleton into something else in this case?

A singleton directly or a singleton factory are basically the same thing - an opaque reference to something - a hidden dependency. With a global text search you can find these dependencies so neither option makes the situation better or worse.
Dependency injection means that you're publicly declaring that for instance A to work it needs an instance of B (or an instance which conforms to protocol C is a better dependency situation). This requires that you instantiate B somewhere and pass it to A.
From a test point of view dependency injection is far superior, because you generally want to create a mock version of B and use that to test A. The test injects the instance to use. Testing singletons is a pain...
So, ideally, the first class involved would create an instance of B and pass it to the other classes that need it, and that instance gets passed on from there.

Related

Dependency Injection and/vs Global Singleton

I am new to dependency injection pattern. I love the idea, but struggle to apply it to my case. I have a singleton object, let’s call it X, which I need often in many parts of my program, in many different classes, sometimes deep in the call stack. Usually I would implement this as a globally available singleton. How is this implemented within the DI pattern, specifically with .NET Core DI container? I understand I need to register X with the DI container as a singleton, but how then I get access to it? DI will instantiate classes with constructors which will take reference to X, that’s great – but I need X deep within the call hierarchy, within my own objects which .NET Core or DI container know nothing about, in objects that were created using new rather than instantiated by the DI container.
I guess my question is – how does global singleton pattern aligns/implemented by/replaced by/avoided with the DI pattern?
Well, "new is glue" (Link). That means if you have new'ed an instance, it is glued to your implementation. You cannot easily exchange it with a different implementation, for example a mock for testing. Like gluing together Lego bricks.
I you want to use proper dependency injection (using a container/framework or not) you need to structure your program in a way that you don't glue your components together, but instead inject them.
Every class is basically at hierarchy level 1 then. You need an instance of your logger? You inject it. You need an instance of a class that needs a logger? You inject it. You want to test your logging mechanism? Easy, you just inject something that conforms to your logger interface that logs into a list and the at the end of your test you can check your list and see if all the required logs are there. That is something you can automate (in contrast to using your normal logging mechanism and checking the logfiles by hand).
That means in the end, you don't really have a hierarchy, because every class you have just gets their dependencies injected and it will be the container/framework or your controlling code that determines what that means for the order of instantiation of objects.
As far as design patterns go, allow me an observation: even now, you don't need a singleton. Right now in your program, it would work if you had a plain global variable. But I guess you read that global variables are "bad". And design patterns are "good". And since you need a global variable and singleton delivers a global variable, why use the "bad", when you can use the "good" right? Well, the problem is, even with a singleton, the global variable is bad. It's a drawback of the pattern, a toad you have to swallow for the singleton logic to work. In your case, you don't need the singleton logic, but you like the taste of toads. So you created a singleton. Don't do that with design patterns. Read them very carefully and make sure you use them for the intended purpose, not because you like their side-effects or because it feels good to use a design pattern.
Just an idea and maybe I need your thought:
public static class DependencyResolver
{
public static Func<IServiceProvider> GetServiceProvider;
}
Then in Startup:
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
DependencyResolver.GetServiceProvider = () => { return serviceProvider; };
}
And now in any deed class:
DependencyResolver.GetServiceProvider().GetService<IService>();
Here's a simplified example of how this would work without a singleton.
This example assumes that your project is built in the following way:
the entry point is main
main creates an instance of class GuiCreator, then calls the method createAndRunGUI()
everything else is handled by that method
So your simplified code looks like this:
// main
// ... (boilerplate)
container = new Container();
gui = new GuiCreator(container.getDatabase(), container.getLogger(), container.getOtherDependency());
gui.createAndRunGUI();
// ... (boilerplate)
// GuiCreator
public class GuiCreator {
private IDatabase db;
private ILogger log;
private IOtherDependency other;
public GuiCreator(IDatabase newdb, ILogger newlog, IOtherDependency newother) {
db = newdb;
log = newlog;
other = newother;
}
public void createAndRunGUI() {
// do stuff
}
}
The Container class is where you actually define which implementations will be used, while the GuiCreator contructor takes interfaces as arguments. Now let's say the implementation of ILogger you choose has itself a dependency, defined by an interface its contructor takes as argument. The Container knows this and resolves it accordingly by instantiating the Logger as new LoggerImplementation(getLoggerDependency());. This goes on for the entire dependency chain.
So in essence:
All classes keep instances of interfaces they depend upon as members.
These members are set in the respective constructor.
The entire dependency chain is thus resolved when the first object is instantiated. Note that there might/should be some lazy loading involved here.
The only places where the container's methods are accessed to create instances are in main and inside the container itself:
Any class used in main receives its dependencies from main's container instance.
Any class not used in main, but rather used only as a dependency, is instantiated by the container and receives its dependencies from within there.
Any class used neither in main nor indirectly as a dependency somewhere below the classes used in main will obviously never be instantiated.
Thus, no class actually needs a reference to the container. In fact, no class needs to know there even is a container in your project. All they know is which interfaces they personally need.
The Container can either be provided by some third party library/framework or you can code it yourself. Typically, it will use some configuration file to determine which implementations are actually supposed to be used for the various interfaces. Third party containers will usually perform some sort of code analysis supported by annotations to "autowire" implementations, so if you go with a ready-made tool, make sure you read up on how that part works because it will generally make your life easier down the road.

How to apply Dependency injection when not all dependencies are always used?

I am trying to understand DI. Since I don't write unit tests (yet), the biggest advantage for me is the decoupling of classes and the management/control of dependencies.
But there's one question: what if I have a class A (controller), that instantiates class B (a listener), and class B will - under certain circumstances - instantiate class C (a mailer)?
According to the DI principle, I have to create C and pass it to B. What if I don't need C during a request? Do I have to create some logic for the Dependency Injection first?
According to the DI principle, I have to create C and pass it to B. What if I don't need C during a request? Do I have to create some logic for the Dependency Injection first?
This shouldn't be a problem because injection constructors should be simple:
An Injection Constructor should do no more than receiving the dependencies.
When you do this, object creation is really fast and reliable, and it doesn't matter whether or not a consumer always uses all of its dependencies.

Openrasta: Swap instance in dependency resolver

Suppose I register some instance in OpenRasta's dependency resolver using
resolver.AddDependencyInstance(IInterface, instance, DependencyLifetime.Singleton)
Now if I want to swap that instance later, say to reread fresh data from the db, is another call to resolver.AddDependencyInstance the right thing to do?
Checking the InternalDependencyResolver implementation, it seems to be fine. However I'm asking because the behavior is not defined (in openrasta's sources, where I checked), and the method prefix "Add" is suggestive of different behavior.
I wouldn't use Singleton if you have to swap the instance at some point.
Use DependencyLifetime.Transient and have a constructor injection in the class where you need the new instance

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)

Practical Singleton & Dependency Injection question

Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in my application. Now I have some class in my application which needs to be able to check a certain permission in one of its methods. This class's constructor is currently public, i.e. used by API users.
Until a couple of weeks ago, I would have simply had my class call the following pseudo-code somewhere:
PermissionManager.getInstance().isReadPermissionEnabled(this)
But since I have noticed everyone here hating singletons + this kind of coupling, I was wondering what the better solution would be, since the arguments I have read against singletons seem to make sense (not testable, high coupling, etc.).
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Or am I going about this all wrong and should have a non-public constructor and a factory somewhere which passes in the instance of PermissionManager for me?
Additional info Note that when I say "Dependency Injection", I'm talking about the DI Pattern...I am not using any DI framework like Guice or Spring. (...yet)
If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you.
If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager.
You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager).
One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like:
PermissionManager mManager = null;
public PermissionManager Permissions
{
if (mManager == null)
{
return mManager;
}
return PermissionManager.getInstance();
}
Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and that's what your other class should reference so a dummy implementation can be substituted more easily during testing.
You can indeed start by injecting the PermissionManager. This will make your class more testable.
If this causes problems for the users of that class you can have them use a factory method or an abstract factory. Or you can add a parameterless constructor that for them to call that injects the PermissionManager while your tests use another constructor that you can use to mock the PermissionManager.
Decoupling your classes more makes your classes more flexible but it can also make them harder to use. It depends on the situation what you'll need. If you only have one PermissionManager and have no problem testing the classes that use it then there's no reason to use DI. If you want people to be able to add their own PermissionManager implementation then DI is the way to go.
If you are subscribing to the dependency injection way of doing things, whatever classes need your PermissionManager should have it injected as an object instance. The mechanism that controls its instantiation (to enforce the singleton nature) works at a higher level. If you use a dependency injection framework like Guice, it can do the enforcement work. If you are doing your object wiring by hand, dependency injection favors grouping code that does instantiation (new operator work) away from your business logic.
Either way, though, the classic "capital-S" Singleton is generally seen as an anti-pattern in the context of dependency injection.
These posts have been insightful for me in the past:
Using Dependency Injection to Avoid Singletons
How to Think About the "new" Operator with Respect to Unit Testing
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Yes, this is all you need to do. Whether a dependency is a singleton / per request / per thread or a factory method is the responsibility of your container and configuration. In the .net world we would ideally have the dependency on an IPermissionsManager interface to further reduce coupling, I assume this is best practice in Java too.
The singleton pattern is not bad by itself, what makes it ugly is the way it's commonly used, as being the requirement of only wanting a single instance of a certain class, which I think it's a big mistake.
In this case I'd make PermissionManager a static class unless for any reason you need it to be an instanciable type.

Resources