Autofac Binding at Runtime

微笑、不失礼 提交于 2019-12-05 18:43:30

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