Autofac Binding at Runtime

后端 未结 1 1019
深忆病人
深忆病人 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();
                // etc
            }
        }
    }
    

    Registration:

    builder.Register(
        c=> new ExportFactory(c.Resolve()))));
    builder.RegisterType();
    builder.RegisterType();
    

    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)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题