【问题标题】:autofac xml configurationautofac xml配置
【发布时间】:2011-07-29 11:48:37
【问题描述】:

我正在使用带有 xml 配置的 autofac 框架。我有一个问题,情况是这样的。我有一个名为 ApplicationConfig 的类,它包含一个实现接口的对象数组。我有两种方法开始和结束。这个想法是在应用程序开始时调用 start 方法,在结束时调用 Finish。

为了设置我调用 SetConfigurations 的对象,它具有可变数量的参数。

代码如下:

public class ApplicationConfig
{
    private IAppConfiguration[] configurators;

    public void SetConfigurations(params IAppConfiguration[] appConfigs)
    {
        this.configurators = appConfigs ?? new IAppConfiguration[0];
    }

    public void Start()
    {
        foreach (IAppConfiguration conf in this.configurators)
            conf.OnStart();
    }

    public void Finish()
    {
        foreach (IAppConfiguration conf in this.configurators)
            conf.OnFinish();
    }
}

xml

<component type="SPCore.ApplicationConfig, SPCore"
    instance-scope="single-instance">
</component>

我只是想知道是否可以通过 xml 配置将在应用程序开始时启动的组件,而不是 SetConfigurations。我在应用程序代码中使用SetConfigurations

所以我想要这样的东西。

类构造函数

public ApplicationConfig(params IAppConfiguration[] appConfigs)
{
    this.configurators = appConfigs;
}

xml

<component type="SPCore.ApplicationConfiguration.ConfigurationParamters, SPCore"
    instance-scope="single-instance">
</component>

<component type="SPCore.ApplicationConfig, SPCore" instance-scope="single-instance">
    <parameters>
        <parameter>--Any componet--</parameter>
        <parameter>--Any componet--</parameter>
        ....
        ....
        <parameter>--Any componet--</parameter>
    </parameters>
</component>

我不知道如何为其他组件的构造函数指定参数..

所以,我希望能够在不编译的情况下配置应用程序。

【问题讨论】:

    标签: xml dependency-injection ioc-container autofac


    【解决方案1】:

    Autofac 的 XML 配置不支持这种情况。

    实现您所追求的最简单的方法是在配置对象上使用 IStartable (http://code.google.com/p/autofac/wiki/Startable) 和 IDisposable,而不是一个ApplicationConfig 类。 Autofac 会自动调用Start()Dispose()

    如果您确实需要让ApplicationConfig 类编排开始/结束过程,您可以控制注册哪些IApplicationConfiguration 组件。默认情况下,Autofac 会将IApplicationConfiguration所有 实现注入到appConfigs 构造函数参数中,因为它是一个数组并且Autofac 对数组类型有特殊处理。只需为您需要的每个 IApplicationConfigurations 添加 &lt;component&gt; 标签,并排除您不需要的标签。

    希望对你有帮助,

    尼克

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多