1

Though both are correct but which of the following is the recommended way:

public class MyService(MyRepository ...) {
    ...
}

or

public class MyService() {
    myRepository = CreateMyRepository();
}

protected MyRepository CreateMyRepository() {
    ...
}

The former would mean that that ought to be a public getter for the repository, which defeats the purpose of allowing only the service to control the repository.

2 Answers2

1

First one. That is loosely coupled. It means that you can decide how to instantiate MyRepository or even provide a subclass to override behaviour. It also helps to instantiate MyRepository only once and use same instance in multiple places.

Also, see more What is dependency injection?

0

It depends on your requirement but I would recommend as shown below example.

Public Constructor useful in Dependency Injection.

Protected Constructor can be used its own class and subclasses(Useful in Singleton Design Pattern). Its also useful Constructor for an Abstract class.

Private Constructor can be used in its own class and ensures there should not be more than one object (useful in Singleton Design Pattern, Builder Design Pattern).

 class MyService {
      private MyRepository myRepository;

      public MyService(MyRepository myRepository){
          this.myRepository= myRepository;  

      }

      public String getMyRepository() { return myRepository; }

       public void setMyRepository(MyRepository myRepository)
       {    
       this.myRepository= myRepository;
      }

    }
Narayan Yerrabachu
  • 1,714
  • 1
  • 19
  • 31