【问题标题】:StructureMap/Autofac: how to create objects based on web.config settingsStructureMap/Autofac:如何根据 web.config 设置创建对象
【发布时间】:2012-12-18 03:23:36
【问题描述】:

我有一个 ConfigurationReader 类,我正在尝试使用 StructureMap 或 AutoFac 进行连接(我还没有确定我正在使用哪个容器)。

public class ConfigurationReader {
  private string _filePath;
  public ConfigurationReader(string filePath){
     this._filePath = filePath;
  }
   public IList<Baz> ListStuff(){
    //do something with _filePath;
   }

}

根据应用程序的配置方式,此类的实例将有 1..n 个(web.config 将包含一个分隔的文件列表)。我正在寻找任何一个 IoC 容器中的扩展点,它允许我利用它们来创建 ConfigurationReader 的实例。

【问题讨论】:

    标签: asp.net-mvc inversion-of-control structuremap autofac


    【解决方案1】:

    好吧,在 AutoFac 中,您只需在 Container 中注册每一个(例如在 Application_Start 期间)。

    当您需要读取所有配置时,您可以将依赖项添加到 IEnumerable&lt;ConfigurationReader&gt;(或 IConfigurationReader,如果您决定提取接口),它将为您提供所有配置。

    类似这样的:

    var builder = new ContainerBuilder();
    foreach(var file in ConfigurationManager.AppSettings[yourKey].Split(',')) 
    {
        var fileName = file;
        builder.Register(c => new ConfigurationReader(fileName));
    }
    DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
    

    如果您提取接口,那么您可能希望通过在末尾添加.AsImplementedInterfaces().As&lt;IConfigurationReader&gt;() 来注册。

    【讨论】:

    • 认为有一个与 lambda 访问你的 foreach 循环变量有关的错误。
    • 你是对的,应该改变它以供本地参考。我会改的。
    • 像魅力一样工作。 Muchas Gracias 先生。
    • Fue un placer,米奇先生:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多