Search code examples
c#autofacinstantiation.net-4.8

Autofac - dynamic instantiation: passing constructor manually


I use dynamic instantiation in AutoFac:

   public class X: I_X
   {
      public X(String p1, String p2)
      {
          ...
      }
   }

   public class A: I_A
   {
      public A(Func<String, String, I_X> x_Factory)
      {
         I_X my_x = x_Factory("one", "two");
         ...
      }
   }

Autofac resolves this as expected.

But suppose I were to use this code in a DLL that is also used in parallel by other projects without AutoFac support: How would I need to prepare the parameter "x_Factory" for the constructor of "A" and pass it so that this works?

   var manual_x_Fac = <what has to be done?>

   var a_object = new A(manual_x_Fac)

I would be happy if someone could help me. Thank you

EDIT:

Sorry, but I forgot to mention that I am still forced to work with the .Net Framework 4.8. The language version is therefore C# 8.0 (7.3).

For it to really help, the solution should also work with vb.net.


Solution

  • You can just create a Func delegate for example using lambda expressions:

    var manual_x_Fac = (string s, string s1) => new X(s, s1);
    var a_object = new A(manual_x_Fac);
    

    For older versions of the compiler you will need to specify the delegate type exlicitly:

    Func<string, string, X> manual_x_Fac = (s, s1) => new X(s, s1);
    

    Which is even more convenient if you inline the parameter:

    var a_object = new A((s, s1) => new X(s, s1));
    

    UPD

    VB.NET version can look something like the following:

    Dim manual_x_Fac As Func(Of String, String, X) = 
        Function(ByVal s As String, ByVal s1 As String) New X(s, s1)