Dagger2 - singleton annotation issue [duplicate] - singleton

I just tested out Dagger 2 and I am having some strange behaviour regarding the singleton annotation. I created some test code to show my problem.
My Module:
#Module
public class App {
#Provides
#Singleton
ThingA provideThingA(){
return new ConcreteThingA();
}
}
Interface of the thing I want in singleton:
public interface ThingA {
void showMyId();
}
Implementation:
public class ConcreteThingA implements ThingA {
#Override
public void showMyId() {
System.out.println(this);
}
}
Code that executes Dagger:
public void doStuff() {
ThingA thingA=DaggerThingAComponent.create().provideThingA();
ThingA thingB=DaggerThingAComponent.create().provideThingA();
System.out.println("Hello");
}
And here is a screenshot showing that I do not get the same instance when I ask for it twice. Have I missed something fundamental? ThingA is just a silly name and in my actual application I would like to have this singleton behaviour on my services.

The trick is that Dagger enforces scope/lifecycle through components, and you've created two separate components here:
ThingA thingA = DaggerThingAComponent.create().provideThingA();
ThingA thingB = DaggerThingAComponent.create().provideThingA();
Each time you create the new top-level #Singleton-annotated Component, Dagger creates a brand new object graph with a brand new container for each #Singleton object. You should have this instead:
ThingAComponent component = DaggerThingAComponent.create();
ThingA thingA = component.provideThingA();
ThingA thingB = component.provideThingA(); // thingA == thingB
Of course, anything further accessed through the dependency graph all comes from the same component, so this will preserve the singleton behavior you're looking for.
In most cases, you should not need to pass around the Component: The Component should be used for top-level components, and anything accessible through the injector should #Inject its dependencies (which means it shouldn't need a reference to the component itself). This might appear problematic during the migration to DI or Dagger, but creating multiple #Singleton components is not the way around it. Instead, try one of the following:
If you need multiple instances of something, you can always inject Provider<T> instead of T whether or not you've created a #Provides method. For that matter, you can inject a Lazy<T> if you only need zero or one copies of a particular dependency, particularly if the creation of that object is particularly heavy.
You can #Inject the component itself if you need it deep within the object graph, though it's always preferable to #Inject Provider<T> tProvider instead of #Inject YourComponent just to call YourComponent.getT.
In some cases, including Android, it may make sense to save the component to a globally-accessible field, either as an instance field in your Application or as a static field somewhere else. This is specifically because Android creates objects on its own, reflectively, rather than getting injected instances from the graph. For all other cases, inject your dependencies to avoid needing to pass around the component.
See also: Bindings in the graph from the Dagger 2 Users Guide

Related

Benefits of an abstract class with a factory constructor?

I've recently run into some examples that make use of abstract classes as interfaces but also add factory constructors to the abstract interface so it can in a sense be "newed" up. For example:
abstract class WidgetService {
factory WidgetService() = ConcreteWidgetService;
Widget getWidget();
void saveWidget(Widget widget);
}
class ConcreteWidgetService extends BaseWidgetService implements WidgetService {
WidgetService();
Widget getWidget() {
// code to get widget here
}
void saveWidget(Widget widget) {
// code to save widget here
}
}
Usages of this service would be in some other service or component like so:
WidgetService _service = new WidgetService();
Based on my understanding of this sample, the line above would essentially "new" up a WidgetService, which usually produces an warning from the Dart analyzer, and said service variable would actually be an instance of ConcreateWidgetService based on the assignment of the ConcreateWidgetService to the factory constructor of the WidgetService.
Is there a benefit to this approach? From my OOP experience, I've used abstract classes/interfaces to program against when I didn't know the concrete type I would be given. Here it seems we are assigning the concrete type immediately to the abstract factory constructor. I guess my second question would be in this instance why not just use the ConcreteWidgetService directly here instead of repeating all the method signatures?
In your example the benefits are limited but in more complex situations the benefits become more clear.
A factory constructor allows you more control about what the constructor returns. It can return an instance of a subclass or an already existing (cached) instance.
It can return different concrete implementations based on a constructor parameter:
abstract class WidgetService {
WidgetService _cached;
factory WidgetService(String type) {
switch (type) {
case 'a':
return ConcreteWidgetServiceA();
case 'b':
return ConcreteWidgetServiceB();
default:
return _cached ??= DummyWidgetServiceA();
}
}
Widget getWidget();
void saveWidget(Widget widget);
}
Your example seems to be a preparation to be extended eventually to such a more flexible approach.
In Dart, all classes are also automatically interfaces. There's nothing strange about creating a instance of - 'newing up' - an 'interface', because it's actually just creating an instance of a class.
The purpose of some abstract classes is specifically to define an interface, but they have factory constructors that return a 'default implementation' of themselves.
For instance:
void main() {
var v = new Map();
print(v.runtimeType);
}
prints: _InternalLinkedHashMap - the (current) default implementation of Map.
Core library users can create and using instances of Map without knowing or caring about the implementation they actually get. The library authors may change the implementation without breaking anyone's code.
Of course, other classes may implement Map also.
With respect to your code sample, WidgetService _service = new WidgetService(); does not produce an analyzer warning. See this example on DartPad (Note I fixed a couple of errors in your sample).
I was initially confused by:
factory WidgetService() = ConcreteWidgetService;
instead of:
factory WidgetService() => new ConcreteWidgetService();
but it seems to work.

Guice Names.bindProperties(binder(), properties) on output of a module?

I use an external service to provide properties, but want to make those properties available as #Named(..) vars. Trying to do this in a configure method fails with npe:
Names.bindProperties(binder(), myPropRetriever.getProperties());
is failing because the myPropRetriever isn't appearing until guice has done it's work. I can see why this makes sense - anyone know of any funky hacks that might work around though? Would be handy in this instance..
Thanks to durron597 for the pointer to the related question which gave me enough to figure out. The answer is to use a child injector to take action on the previous injectors output. Example below:
Injector propInjector = Guice.createInjector(new PropertiesModule());
PropertiesService propService = propInjector.getInstance(PropertiesService.class);
Injector injector = propInjector.createChildInjector(new MyModule(Objects.firstNonNull(propService.getProperties(), new Properties())));
Injector is now your injector for the remainder of the app.
And then in MyModule you can take action on the created objects:
public class MyModule extends AbstractModule {
private final Properties properties;
public MyModule(Properties properties){
this.properties=properties;
}
#Override
protected void configure() {
// export all the properties as bindings
Names.bindProperties(binder(), properties);
// move on to bindings
// bind(..);
}
}
In case it helps anyone else..!

How to Solve Circular Dependency

Hi I have a problem with the structure of my code, it somehow goes into Circular Dependency. Here is an explanation of how my code looks like:
I have a ProjectA contains BaseProcessor and BaseProcessor has a reference to a class called Structure in ProjectB. Inside BaseProcessor, there is an instance of Structure as a variable.
In projectB there are someother classes such as Pricing, Transaction etc.
Every class in ProjectB has a base class called BaseStructure i.e. Structure, Pricing and Transaction classes all inherited from BaseStructure.
Now in Pricing and Transaction classes, I want to call a method in BaseProcessor class from BaseStructure class which causing Circular Dependency.
What I have tried is:
Using Unity, but I didn't figure out how to make it work because I try to use function like:
unityContainer.ReferenceType(IBaseProcessor, BaseProcessor)
in BaseStructure then it will need a reference of BaseProcessor which also cause Circular Dependency.
And I've also tried creating an interface of IBaseProcessor and create a function(the function I want to call) declaration in this interface. And let both BaseProcessor and BaseStructure inherit this interface. But how can I call the function in Pricing and Transaction class without create an instance of BaseProcessor?
Can anyone please tell me how to resolve this problem other than using reflection?
Any help will be much appreciated. Thanks :)
You could use the lazy resolution:
public class Pricing {
private Lazy<BaseProcessor> proc;
public Pricing(Lazy<BaseProcessor> proc) {
this.proc = proc;
}
void Foo() {
this.proc.Value.DoSomethin();
}
}
Note that you haven't to register the Lazy because Unity will resolve it by BaseProcessor registration.
Your DI container can't help solving the circular reference, since it is the dependency structure of the application that prevents objects from being created. Even without a DI container, you can't construct your object graphs without some special 'tricks'.
Do note that in most cases cyclic dependency graphs are a sign of a design flaw in your application, so you might want to consider taking a very close look at your design and see if this can't be solved by extracting logic into separate classes.
But if this is not an option, there are basically two ways of resolving this cyclic dependency graph. Either you need to fallback to property injection, or need to postpone resolving the component with a factory, Func<T>, or like #onof proposed with a Lazy<T>.
Within these two flavors, there are a lot of possible ways to do this, for instance by falling back to property injection into your application (excuse my C#):
public class BaseStructure {
public BaseStructure(IDependency d1) { ... }
// Break the dependency cycle using a property
public IBaseProcessor Processor { get; set; }
}
This moves the IBaseProcessor dependency from the constructor to a property and allows you to set it after the graph is constructed. Here's an example of an object graph that is built manually:
var structure = new Structure(new SomeDependency());
var processor = new BaseProcessor(structure);
// Set the property after the graph has been constructed.
structure.Processor = processor;
A better option is to hide the property inside your Composition Root. This makes your application design cleaner, since you can keep using constructor injection. Example:
public class BaseStructure {
// vanilla constructor injection here
public BaseStructure(IDependency d1, IBaseProcessor processor) { ... }
}
// Defined inside your Composition Root.
private class CyclicDependencyBreakingProcessor : IBaseProcessor {
public IBaseProcessor WrappedProcessor { get; set; }
void IBaseProcessor.TheMethod() {
// forward the call to the real processor.
this.WrappedProcessor.TheMethod();
}
}
Now instead of injecting the BaseProcessor into your Structure, you inject the CyclicDependencyBreakingProcessor, which will be further initialized after the construction of the graph:
var cyclicBreaker = new CyclicDependencyBreakingProcessor();
var processor = new BaseProcessor(new Structure(new SomeDependency(), cyclicBreaker));
// Set the property after the graph has been constructed.
cyclicBreaker.WrappedProcessor = processor;
This is basically the same as before, but now the application stays oblivious from the fact that there is a cyclic dependency that needed to be broken.
Instead of using property injection, you can also use Lazy<T>, but just as with the property injection, it is best to hide this implementation detail inside your Composition Root, and don't let Lazy<T> values leak into your application, since this just adds noise to your application, which makes your code more complex and harder to test. Besides, the application shouldn't care that the dependency injection is delayed. Just as with Func<T> (and IEnumerable<T>), when injecting a Lazy<T> the dependency is defined with a particular implementation in mind and we're leaking implementation details. So it's better to do the following:
public class BaseStructure {
// vanilla constructor injection here
public BaseStructure(IDependency d1, IBaseProcessor processor) { ... }
}
// Defined inside your Composition Root.
public class CyclicDependencyBreakingProcessor : IBaseProcessor {
public CyclicDependencyBreakingBaseProcessor(Lazy<IBaseProcessor> processor) {...}
void IBaseProcessor.TheMethod() {
this.processor.Value.TheMethod();
}
}
With the following wiring:
IBaseProcessor value = null;
var cyclicBreaker = new CyclicDependencyBreakingProcessor(
new Lazy<IBaseProcessor>(() => value));
var processor = new BaseProcessor(new Structure(new SomeDependency(), cyclicBreaker));
// Set the value after the graph has been constructed.
value = processor;
Up until now I only showed how to build up the object graph manually. When doing this using a DI container, you usually want to let the DI container build up the complete graph for you, since this yields a more maintainable Composition Root. But this can make it a bit more tricky to break the cyclic dependencies. In most cases the trick is to register the component that you want to break with a caching lifestyle (basically anything else than transient). Per Web Request Lifestyle for instance. This allows you to get the same instance in a lazy fashion.
Using the last CyclicDependencyBreakingProcessor example, we can create the following Unity registration:
container.Register<BaseProcessor>(new PerRequestLifetimeManager());
container.RegisterType<IStructure, Structure>();
container.RegisterType<IDependency, SomeDependenc>();
container.Register<IBaseProcessor>(new InjectionFactory(c =>
new CyclicDependencyBreakingProcessor(
new Lazy<IBaseProcessor>(() => c.GetInstance<BaseProcessor>())));

OO Design Issue related to subclassing

I have a parent bean having one instance variable like below :
public Class ParentBean {
protected boolean show; // this variable will be used to show some UI component
public void action() {
// update show variable here
}
public boolean isShow() {
return show;
}
}
Is it a good design if I want to reuse the "show" variable in a child bean (to show other UI component specific to child bean ) as shown below :
public Class ChildBean extends ParentBean {
// override the action method from parent bean
public void action() {
// update show variable here
show = true /false;
}
}
In effect , show variable is being updated by "childBean" by overriding action() method.
Is this a good design practice ? Otherwise same thing has to be repeated in ChildBean to get this work done.
If you use the show variable for the same purpose in the subclass, as you seem to be doing in this example, then obviously you should reuse it, because otherwise you just end up writing the same code twice, which is contrary to the point of OOP.
In general, in OOP, it is common to override superclass methods in subclasses, as well as modifying superclass instance variables, as long as you know what the variable you are modifying is being used for (you don't want to be randomly changing instance variables in classes that you don't completely understand, or don't have access to the source of, because you don't want any unfortunate side effects), so when it's your own code, this is absolutely fine.
As a general guideline, if your options are either to copy and paste a massive hunk of code and use it unchanged, or subclass and use the superclass' instance variables or functions, it's better to subclass. Otherwise, you're missing out on the point of OOP.
Changing the value in subclass will not affect superclass variable
This is fine with respect to the design. When a subclass object is instantiated, it will have a different copy of variable. and If superclass object is instantiated it will have different copy.
It is. Having a protected variable means you are allowed to modify it into parent or children classes (remember every single instance of each class has its own property values). So, if you have some generic functionality which is valuable for all the children:
Parent class:
public void action(){
//update show variable here
show = true;
}
Appart from that, if you want to add some extra functionality in a specifical child:
Child class:
#Override
public void action(){
super.action();
//Extra functionality goes here
//You can also access parent's 'protected' fields
if (show){
System.out.println("Shown");
}
}
An example of the use:
Parent p = new Parent();
p.action();//Prints nothing
Child c = new Child();
p.action();//Prints 'shown'

wicket and AtUnit

I've started playing with Wicket and I've chosen Guice as dependency injection framework. Now I'm trying to learn how to write a unit test for a WebPage object.
I googled a bit and I've found this post but it mentioned AtUnit so I decided to give it a try.
My WebPage class looks like this
public class MyWebPage extends WebPage
{
#Inject MyService service;
public MyWebPage()
{
//here I build my components and use injected object.
service.get(id);
....
}
}
I created mock to replace any production MyServiceImpl with it and I guess that Guice in hand with AtUnit should inject it.
Now the problems are:
AtUnit expects that I mark target object with #Unit - that is all right as I can pass already created object to WicketTester
#Unit MyWebPage page = new MyWebPage();
wicketTester.startPage(page);
but usually I would call startPage with class name.
I think AtUnit expects as well that a target object is market with #Inject so AtUnit can create and manage it - but I get an org.apache.wicket.WicketRuntimeException: There is no application attached to current thread main. Can I instruct AtUnit to use application from wicketTester?
Because I don't use #Inject at MyWebPage (I think) all object that should be injected by Guice are null (in my example the service reference is null)
I really can't find anything about AtUnit inside Wicket environment. Am I doing something wrong, am I missing something?
I don't know AtUnit but I use wicket with guice and TestNG. I imagine that AtUnit should work the same way. The important point is the creation of the web application with the use of guice.
Here how I bind all this stuff together for my tests.
I have an abstract base class for all my tests:
public abstract class TesterWicket<T extends Component> {
#BeforeClass
public void buildMockedTester() {
System.out.println("TesterWww.buildMockedTester");
injector = Guice.createInjector(buildModules());
CoachWebApplicationFactory instance =
injector.getInstance(CoachWebApplicationFactory.class);
WebApplication application = instance.buildWebApplication();
tester = new WicketTester(application);
}
protected abstract List<Module> buildModules();
The initialization is done for every test class. The subclass defines the necessary modules for the test in the buildModules method.
In my IWebApplicationFactory I add the GuiceComponentInjector. That way, after all component instantiation, the fields annotated with #Inject are filled by Guice:
public class CoachWebApplicationFactory implements IWebApplicationFactory {
private static Logger LOG = LoggerFactory.getLogger(CoachWebApplicationFactory.class);
private final Injector injector;
#Inject
public CoachWebApplicationFactory(Injector injector) {
this.injector = injector;
}
public WebApplication createApplication(WicketFilter filter) {
WebApplication app = injector.getInstance(WebApplication.class);
Application.set(app);
app.addComponentInstantiationListener(new GuiceComponentInjector(app, injector));
return app;
}
}