Search code examples
androidguicerobolectricroboguice

roboguice - how to manually create a new object


I have a Customer class and i have injected it's dependencies with the @Inject annotation. I'd like to create a method in this class that returns a new instance of the class.

class Customer{

    //the DataSource class is annotated with @Singleton
    @Inject protected DataSource dataSource;

    public DataSource getDatasource(){
        return dataSource;
    }

    public Customer newInstance(){
        return new Customer();
    }
}

In my activity i'm having one customer injected via the @Inject annotation. In the onCreate() method i'm getting another Customer instance by calling customer.newInstance() but when i do the following, the datasource for the second Customer object is null. How do i create a new object on demand through RoboGuice ensuring it has its dependencies?

if(customer.newInstance().getDatasource() == null){
    //This gets logged
    Log.d("DEBUG", "2nd customer's datasource is null");
}

Any help would be much appreciated.


Solution

  • Figured it out with the following.

    class Customer{
    
        //the DataSource class is annotated with @Singleton
        @Inject protected DataSource dataSource;
    
        @Inject protected Injector injector;
    
        public DataSource getDatasource(){
            return dataSource;
        }
    
        public Customer newInstance(){
            return injector.getInstance(getClass());
        }
    }