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