autofac xml配置

问题描述 投票:2回答:1

我正在使用带有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个回答
2
投票

Autofac的XML配置不支持此方案。

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

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

希望这可以帮助,

缺口

© www.soinside.com 2019 - 2024. All rights reserved.