autofac xml配置

时间:2011-07-29 11:48:37

标签: xml dependency-injection ioc-container autofac

我正在使用带有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>

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

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

1 个答案:

答案 0 :(得分:2)

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

实现目标的最简单方法是在配置对象上使用IStartable(http://code.google.com/p/autofac/wiki/Startable)和IDisposable ,根本没有ApplicationConfig课程。 Autofac会自动调用Start()Dispose()

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

希望这有帮助,

尼克