Search This Blog

Friday, July 22, 2011

Autofac create different classes (components) based on a parameter value

public interface A
   {
       void p();
   }

   public class B : A
   {
       public void p()
       { }
   }

   public class C : A
   {
       public void p()
       { }
   }

   //create different classes (components) based on a parameter value
   class Program
   {
       //Selection of an Implementer based on a Parameter Value
       static void Main()
       {  
           var builder = new ContainerBuilder();
           //c - container, p - parameters
           builder.Register<A>((c, p) =>
           {
               //we cannot cast directly to int as parameter string has to be parsed in order to get int
               string accountIdStr = p.Named<string>("id");
               int accountId = int.Parse(accountIdStr);
               if (accountId > 900 )
                   return new C();
               else
                   return new B();
           });

           var container = builder.Build();
           var obj = container.Resolve<A>(new NamedParameter("id", "12345"));

           Console.WriteLine("Obj resolved: " + obj.GetType().ToString());
           Console.WriteLine("Done! Press any key.");
           Console.ReadKey();
       }
   }

No comments:

Post a Comment

If you like this post, please leave a comment :)