Autofac Binding at Runtime

感情迁移 提交于 2019-12-22 08:44:29

问题


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.


回答1:


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);
   }
}


来源:https://stackoverflow.com/questions/10717553/autofac-binding-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!