Implement a factory and let it do the creation or inject everything?

Is it okay to inject a factory and then instantiate many objects inside the constructor?

private readonly SafeClient<AccountProxy, IAccountService> _accountProxy;
private readonly SafeClient<AccountClassProxy, IAccountClassService> _accountClassProxy;
private readonly SafeClient<CarrierProxy, ICarrierService> _carrierProxy;
private readonly SafeClient<TransportationTypeProxy, ITransportationTypeService> _transportationTypeProxy;

public AccountController(ISafeClientFactory clientFactory)
{
    clientFactory.UserName = "user";
    clientFactory.Password = "password";
    _accountProxy = clientFactory.CreateClient<AccountProxy, IAccountService>();
    _accountClassProxy = clientFactory.CreateClient<AccountClassProxy, IAccountClassService>();
    _carrierProxy = clientFactory.CreateClient<CarrierProxy, ICarrierService>();
    _transportationTypeProxy = clientFactory.CreateClient<TransportationTypeProxy, ITransportationTypeService>();
}

      

Or is it better to just add everything? What are the pros and cons? Sorry, I'm new to this business. Thank.

public AccountController(
    ISafeClient<IAccountService> accountProxy,
    ISafeClient<IAccountClassService> accountClassService,
    ISafeClient<ICarrierService> carrierService,
    ISafeClient<ITransportationTypeService> transportService) 
{
     //assignment here
}

      

+3


source to share


2 answers


By injecting a factory into the constructor, you are hiding the real dependencies and have the same disadvantages as you using an antivirus . These disadvantages include:

  • it hides class dependencies, causing runtime errors instead of compile-time errors.
  • it makes the code harder to maintain because it becomes unclear when you introduce change with change
  • it is much more difficult for the consumer of the component to know if the component can have a Captive Dependency and it makes the tools blind; they will not be able to detect these errors.
  • You can hide the fact that the class is using too many dependencies. In other words, it hides the fact that a class can violate the single responsibility principle.


You usually use a factory to delay the construction of a portion of your object graph, but in case you call the factory inside a constructor, you don't delay the construction at all. You don't get additional benefits, only disadvantages.

Thus, it is absolutely correct to inject dependencies directly.

+4


source


I usually go with a second example, and this is the rationale I live in:



If B's โ€‹โ€‹dependency on A can be created at build time for A, then it must be created outside of A and the constructor entered in A. If that is not enough information to create B at build time for A, then enter a factory that can create B. when sufficient information is available.

+4


source







All Articles