4

I'm trying to better understand the pros/cons of instantiating vs injecting in a web application type development.

  1. What are the pros & cons for each?
  2. When should they be used (what sort of scenario we looking at)?
Aeseir
  • 247

1 Answers1

3

1. pros: testability, external configuration of per client implementation rather than "in the code" implementation (think if / else if for each new client). logic is abstracted away

cons: adds complexity, logic is abstracted away

2. You should inject "behavioral" implementations which can have variance based on implementation or environment. Things which don't change could be instantiated

Long winded answer: Injecting gives you the greatest flexibility of configuration of concrete implementations / instantiations. It's a layer of abstraction which allows you to define the "behaviors" of the implementations (the ins / outs) so you can build your entire app around expectations. Then the "fulfillers" of those expectations can be configured.

Client A uses SQL database, Client B uses Oracle database.

Client A calls a method: public User GetUserByID(int id)

Client B calls a method: public User GetUserByID(int id)

if we create an interface which contains something like:

public interface IUserServices{
     User GetUserByID(int id)
}

We can use an Injector to configure which implementation to use. something like this on app startup for client A:

Bind<ClientA_UserServices>.To<IUserServices>(); 

and for client B:

Bind<ClientB_UserServices>.To<IUserServices>(); 

and in the App:

public class DoSomethingWithUserService{
      IUserServices _svc;

      public DoSomethingWithUserService(IUserServices svc)
      {
            _svc = svc;
      }

      public void doSomething()
      {
            User theUser = _svc.GetUserByID(User.ID);
      }
}

now, in addition, you can now unit test DoSomethingWithUserService and pass in a test implementation IUserServices which may use static test data, or Mock data.

hanzolo
  • 3,131
  • 1
  • 20
  • 21