运行时的 Autofac 绑定 [英] Autofac Binding at Runtime
问题描述
我目前使用 Autofac 进行简单的构造函数注入,没有任何问题.但是我想知道的是如何在运行时解决依赖关系.下面的示例显示了我们可以导出文档的多种方式.通过简单的构造函数注入,IExport 的具体实现在运行时得到解决.但是,需要做的是从下拉列表中解决用户选择上的 IExport,这将在我的容器构建后发生.是否有任何示例可以说明我如何实现这一目标?
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.
推荐答案
你应该使用工厂:
public interface IExportFactory
{
IExport CreateNewExport(string type);
}
实施:
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
}
}
}
注册:
builder.Register<IExportFactory>(
c=> new ExportFactory(c.Resolve<IComponentContext>()))));
builder.RegisterType<HTMLformat>();
builder.RegisterType<PDFformat>();
控制器:
public class HomeController : Controller
{
IExportFactory factory;
public HomeController(IExportFactory factory)
{
this.factory = factory;
}
public void ExportDocument(string content)
{
this.factory.CreateNew("html").Run(content);
}
}
这篇关于运行时的 Autofac 绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!