运行时的Autofac绑定 [英] Autofac Binding at Runtime

查看:64
本文介绍了运行时的Autofac绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆