Can I use Ioc pattern to achieve the following goal - dependency-injection

I have two classes implemented the same static methods like the following,
Class A
{
static OpB();
}
Class B
{
static OpB();
}
Can I use Ioc pattern to switch ClassA and ClassB using the configuration?
Or any workaround or suggestions?

The IoC pattern pretty much prohibits you from using static methods because it focuses on creating instances of a type (service). Static methods are not instance methods, so an IoC container would give you an instance but you can't call a static method on an instance.
If it's possible to drop the static qualifier on the OpB() method you'll be able to do what you want using IoC.

Related

How to implement a general class for singleton?

I've been trying to implement a state management project for my design patterns course. I have implemented the singleton because I know that's essential for keeping state of a class. What I would like to do is: Create a general class, so that others could use it in their projects. How do I do that? My code so far:
class StateManager{
static final StateManager _instance = StateManager._singleton();
StateManager._singleton();
factory StateManager(){
return _instance;
}
}
My other solution to try and make it general:
class AppProvider extends StateManager<AppProvider>{
int i = 10;
String data = "adas";
}
class StateManager<T extends AppProvider>{
static final StateManager _instance = StateManager._singleton();
StateManager._singleton();
factory StateManager(){
return _instance;
}
}
I want the AppProvider class to be the client class, and I want the StateManager to automatically handle the fact that AppProvider should be a singleton, and maintain the state of AppProvider.. I really don't know how to do that.
Forcing a class to be a singleton through inheritance alone is not going to work. That's not something that the language supports. Constructors are not inherited, neither are static members, and you need those to access the singleton.
In order to be able to create an instance of a class at all, the class needs a generative constructor.
That generative constructor will create a new instance every time it's invoked, because that's what generative constructors do.
For a subclass to be able to extend a class, the superclass must have an accessible generative constructor too, but at least the superclass can be made abstract.
In order to force a class to be a singleton (if you really want that, because a singleton is really something of an anti-pattern; it makes the class act like it's just a bunch of global variables, and that makes testing harder), each such class needs to have a public static way to access or create the instance, and a private generative constructor.
So, basically, your first approach does what is needed, and since the constructors are not inherited, you need to do that for every singleton class, and there is nothing useful to inherit.
So, there is nothing you can do with inheritance to make singleton-ness be inherited, and you can't even help because everything a singleton needs is static.
A different approach is to make the state classes entirely private, so you don't have to worry about someone else creating instances, and give them a constant generative constructor each, and then only refer to them using const _ThisState() or const _ThatState().
This puts the responsibility on the user (you!) to only create one instance of each state object, but it also gives a very easy way to do that, because const _ThisState() will provide the same instance every time.
Or use the enum pattern, and have:
abstract class State {
static const State thisState = const _ThisState();
static const State thatState = const _ThatState();
const State._();
void handle(Context context, Object argument);
}
class _ThisState implements State {
const _ThisState();
void handle(Context context, Object argument) { ... }
}
class _ThatState implements State {
const _ThatState();
void handle(Context context, Object argument) { ... }
}
and then just refer to the state instances as State.thisState. I find that more readable than creating instances of seemingly unrelated classes.

Ignore mocked object transitive dependencies

When a class implements an interface all we have to do is mock that interface.
However there are some cases when a class doesn't implement an interface, in that case binding the class to a mock leads guice to get the mocked object dependencies.
To clarify:
class A {
#Inject B;
}
class B{
#Inject C;
}
bind(a.class).toInstance(mock(B.class));
In this scenario, I don't care B's dependencies, but guice stills tries to inject C inside B.
Is there a way to avoid this without defining an interface?
First of all, I strongly recommend against using dependency injection in unit tests. When you're unit testing single class you should create it and pass its dependencies directly, through a constructor or methods. You won't have these problems then.
It's another story when you're writing integration tests though. There are several solutions to your problem.
Make sure all your classes receive dependencies only through injectable constructors. This way Guice won't inject anything because the object will be created by Mockito.
Use providers (and scoping, if needed). The following is equivalent to your attempt sans injection into B (I assume that you really meant bind(B.class).toInstance(mock(B.class)):
bind(B.class).toProvider(new Provider<B> {
#Override
public B get() {
return mock(B.class);
}
}).in(Singleton.class);
You should tweak the scope to satisfy your needs.
Using Mockito to partially solve this was quite easy.
You will need to use #Mock and #InjectMocks annotations like this
ATest{
#Mock B;
#InjectMocks A;
public void setUp(){
MockitoAnnotations.initMocks(this);
}
}
This way Mockito will do the inject instead of guice, there are a couple of restrictions to successfully inject the mock.
This works pretty well until your code have a strong dependency on a class.
Lets say inside A i have something like C obj = new C(); and C have injected fields.

DDD: Service and Repositories Instances Injected with DI as Singletons

I've recently been challenged on my view that singletons are only good for logging and configuration. And with Dependency Injection I am now not seeing a reason why you can't use your services or repositories as singletons.
There is no coupling because DI injects a singleton instance through an interface. The only reasonable argument is that your services might have shared state, but if you think about it, services should be stand alone units without any shared state. Yes they do get injected with the repositories but you only have one way that a repository instance is created and passed to the service. Since repositories should never have a shared state I don't see any reasons why it also cannot be a singleton.
So for example a simple service class would look like this:
public class GraphicService : IGraphicService
{
private IGraphicRepository _rep;
public GraphicService(IGraphicRepository rep)
{
_rep = rep;
}
public void CreateGraphic()
{
...
_rep.SaveGraphic(graphic):
}
}
No state is shared in service except repository which also doesn't change or have it's own state.
So the question is, if your services and repositories don't have any state and only passed in, through interface, configuration or anything else that's instantiated the same way they then why wouldn't you have them as singleton?
If you're using the Singleton pattern i.e a static property of a class, then you have the tightly coupling problem.
If you need just a single instance of a class and you're using a DI Container to control its lifetime, then it's not a problem as there are none of the drawbacks. The app doesn't know there is a singleton in place, only the DI Container knows about it.
Bottom line, a single instance of a class is a valid coding requirement, the only issue is how you implement it. The Di Container is the best approach. the Singleton pattern is for quick'n dirty apps where you don't care enough about maintainability and testing.
Some projects use singleton for dependence lookup before dependency injection gets populated. for example iBATIS jpetstore if I'm not mistaken. It's convenient that you can access your dependence gloablly like
public class GraphicService : IGraphicService
{
private IGraphicRepository _rep = GraphicRepository.getInstance();
public void CreateGraphic()
{
...
_rep.SaveGraphic(graphic):
}
}
But this harms testability (for not easy to replace dependence with test doubles) and introduces implicit strong dependence (IGraphicService depends on both the abstraction and the implementation).
Dependeny injection sovles these. I don't see why can't use singleton in your case, but it doesn't add much value when using DI.

IoC - Autowiring for objects that are created inside of components

What bothers me about IoC and autowiring is the usability of IoC for objects that are created.
Lets say I have the a static Utils class, that is used across the system. When I decided to use IoC and DI, I easily changed Utils to be non-static and have all my components receive its instance.
However, auto-wiring works well only for components that are created during bootstrap, for objects that are created during run-time or as response of user operations, and that use Utils, auto-wiring doesn't work. Instead, I have to manually pass instance of Utils to every instance of every object that is created during runtime.
The only way around it that I can see is using the anti-pattern of passing the IoC container around, which I certainly wouldn't want to do.
Is there another way? Or am I forced to pass Utils manually around to every instance and class?
Note: This isn't a question of design. Sure, I could minimize the usage of this metaphorical Utils in various ways, but in many situations it is unavoidable.
The only way around it that I can see is using the anti-pattern of
passing the IoC container around, which I certainly wouldn't want to
do.
The answer is simply: use an abstract factory.
By defining the factory interface in the application and the factory implementation in the Composition Root (your bootstrapper code) you can prevent using the Service Locator anti-pattern. This factory implementation can hold a reference to the container and call it to request instances. Because that implementation is part of your bootstrapping logic, that implementation is a infrastructure component, and you are not using it as a service locator.
Example:
public interface IUnitOfWorkFactory
{
IUnitOfWork CreateNew();
}
Implementation in composition root:
internal class SimpleInjectorUnitOfWorkFactory
: IUnitOfWorkFactory
{
private readonly SimpleInjector.Container container;
public SimpleInjectorUnitOfWorkFactory(Container container)
{
this.container = container;
}
public IUnitOfWork CreateNew()
{
return this.container.GetInstance<IUnitOfWork>();
}
}

Service Locator using static methods

In the code of the project I'm working on I encountered a strange approach.
The UI layer gets dependecies using a sort of Service Locator which is a class with static methods:
public class ServiceManager {
public static MailService getMailService() {
...
}
public static UserInfoService getUserInfoService() {
...
}
...
}
The dependencies that are "distributed" by this class are injected to it using Spring framework.
What could be the reason for this approach? I can see only downsides. Since the locator methods are static, there is no interface. The absence of interface makes it harder to reason about the purpose of the class. Clients of this class are tightly coupled to it (remember, no interface there), making them impossible to reuse elsewhere.
Wouldn't it be much better to let Spring inject dependencies in the UI classes directly?
With most UI frameworks, it is often very hard (if not impossible) to use constructor injection in the UI classes. In that case it is common to revert to the Service Locator pattern, but only -I repeat only- in the UI classes.

Resources