Func<T> - Dynamic Instantiation

Introduction 
 
Think of a scenario where we want more than one instance of a given service; or when we have to make the decision about whether to instantiate a component/service at runtime. For such scenarios, injecting a service as a Direct Dependency or Lazy Dependency will not be enough. Instead, injecting the service dependency as a Func will do, as it provides the dynamism we require. 
 
Using Func<T>
 
Consider the following example, where we have a PaymentProcessor class which has a dependency on the IPaymentGateway service. And, the decision whether to instantiate the payment gateway or not, is based on the user's choice of PaymentMode (say cash or card). The below code shows the use of a Func in this scenario
  1. public interface IPaymentGateway  
  2. {  
  3.     void InitiatePayment(TransactionDetails transactionDetails);  
  4. }  
  5.   
  6. public class PaymentProcessor  
  7. {  
  8.     private Func<IPaymentGateway> _paymentGatewayInitializer;  
  9.     public PaymentProcessor(Func<IPaymentGateway> paymentGatewayInitializer)  
  10.     {   
  11.         _paymentGatewayInitializer = paymentGatewayInitializer;   
  12.     }  
  13.   
  14.     public void ProcessPayment(TransactionDetails transactionDetails)  
  15.     {  
  16.         if(transactionDetails.PaymentMode != PaymentMode.Cash)  
  17.         {  
  18.             using(var paymentGateway = _paymentGatewayInitializer())  
  19.             {  
  20.                 paymentGateway.InitiatePayment(amount);  
  21.             }  
  22.         }  
  23.     }  
  24. }  
It is important to note that there can be a scenario where a user chooses to pay in cash. In this case, we don't need to instantiate IPaymentGateway. Also, we shall have a new instance of the class implementing IPaymentGateway, every time we initiate a new transaction.
 
Why not Lazy<T>?
 
I know, you must be thinking why not use Lazy initialization here? What is the benefit of using Func over Lazy in this scenario? If we use Lazy, the code would look like the following
  1. public class PaymentProcessor  
  2. {  
  3.     private Lazy<IPaymentGateway> _paymentGateway;  
  4.     public PaymentProcessor(Lazy<IPaymentGateway> paymentGateway)  
  5.     {   
  6.         _paymentGateway = paymentGateway;   
  7.     }  
  8.   
  9.     public void ProcessPayment(TransactionDetails transactionDetails)  
  10.     {  
  11.         if(transactionDetails.PaymentMode != PaymentMode.Cash)  
  12.         {  
  13.             _paymentGateway.Value.InitiatePayment(amount); 
  14.         }  
  15.     }  
  16. }  
While everything looks good at first, there is a problem. When the payment gateway is initialized, it is actually resolved in the same scope as the PaymentProcessor. This means that the payment gateway will be held in memory until the time PaymentProcessor is released. And therefore, we will always have the same instance of payment gateway in every transaction. 
 
Register & Resolve 
 
For this article, I'm using Autofac as the DI Container. The registration of the components will be quite simple as shown in the below code
  1. var builder = new ContainerBuilder();  
  2. builder.RegisterType<TransactionDetails>().InstancePerLifetimeScope();  
  3. builder.RegisterType<PaymentProcessor>().InstancePerLifetimeScope();  
  4. builder.RegisterType<IPaymentGateway>().InstancePerLifetimeScope();  
  5.   
  6. var container = builder.Build();  
  7. using(var scope = container.BeginLifetimeScope())  
  8. {  
  9.     // Initialize transactionDetails object here and pass  
  10.     // it to the PaymentProcessor.  
  11.     var paymentProcessor = scope.Resolve<PaymentProcessor>();  
  12.     paymentProcessor.ProcessPayment(transactionDetails);  
  13. }  
Because the IPaymentGateway has been registered as a Func, the container will not resolve it with the PaymentProcessor. In fact, the container leaves it up to the PaymentProcessor to initialize IPaymentGateway using the auto-generated factory method. Therefore, as we can see in the above code, we are initializing the IPaymentGateway using the _paymentGatewayInitializer.
 
Lifetime Scope 
 
In the above example, we have registered the IPaymentGateway as InstancePerLifetimeScope(). This is to say that, every time we resolve the Func<IPaymentGateway> dependency, we will get a new instance of IPaymentGateway. Behind the scenes, Autofac creates an internal scope in which the dependency is resolved. In our case, inside the using block. When we don't need the object anymore, the scope is released and therefore the dependency object is disposed of.
 
However, if we register a component as SingleInstance() and resolve Func<T> multiple times, we will get the same object instance every time.
 
Summary
 
While injecting dependencies, we need to take extra care about when the dependency must be initialized and for how long it should stay in memory. Though there is a lot more to that, being able to identify the nature of our dependency is a good start. 


Similar Articles