Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac Binding at Runtime

I currently use Autofac to do simple constructor injection without any issues. However what I would like to know is how to resolve dependencies at runtime. The example below shows multiple ways in which we can export a document. With simple constructor injection the concrete implementation of IExport is resolved at runtime. However what need to do is to resolve IExport on a user selection from a dropdown list which will happen after the construction of my container. Is there any examples of how I can achieve this?

Public interface IExport
{
   void Run(string content);
}

public class PDFformat : IExport
{ 
   public void Run(string content)
   {
       // export in pdf format
   }
}

public class HTMLformat : IExport
{
   public void Run(string content)
   {
       // export in html format
   }
}

public class RTFformat : IExport
{  
   public void Run(string content)
   {
       // export in rtf format
   }
}

public class HomeController : Controller
{
   IExport Export;

   public HomeController(IExport export)
   {
      Export = export;
   }

   public void ExportDocument(string content)
   {
      Export.Run(content);
   }
}

Any help on this would be much appreciated.

like image 868
Cragly Avatar asked May 23 '12 09:05

Cragly


1 Answers

You should use a factory:

public interface IExportFactory
{
    IExport CreateNewExport(string type);
}

Implementation:

class ExportFactory : IExportFactory
{
    private readonly IComponentContext container;

    public ExportFactory(IComponentContext container)
    {
        this.container = container;
    }

    public IExport CreateNewExport(string type)
    {
        switch (type)
        {
            case: "html":
                return this.container.Resolve<HTMLformat>();
            // etc
        }
    }
}

Registration:

builder.Register<IExportFactory>(
    c=> new ExportFactory(c.Resolve<IComponentContext>()))));
builder.RegisterType<HTMLformat>();
builder.RegisterType<PDFformat>();

Controller:

public class HomeController : Controller
{
   IExportFactory factory;

   public HomeController(IExportFactory factory)
   {
      this.factory = factory;
   }

   public void ExportDocument(string content)
   {
      this.factory.CreateNew("html").Run(content);
   }
}
like image 134
Steven Avatar answered Sep 22 '22 02:09

Steven