Autofac Binding at Runtime

后端 未结 1 1017
深忆病人
深忆病人 2021-01-05 13:32

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

相关标签:
1条回答
  • 2021-01-05 13:55

    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);
       }
    }
    
    0 讨论(0)
提交回复
热议问题