How to instantiate a class based on web.config fil

2019-07-17 07:33发布

问题:

I'm working on an ASP.NET MVC application and I would like to instantiate a class based on settings written in web.config.

<configSections>
    <section name="castle"
        type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>

<castle>
    <components>
        <component
            id="SqlRepository"
            service="GomokuGameAppDomain.IGameRepository, GomokuGameAppDomain"
            type="GomokuGameAppDomain.SqlGameRepository, GomokuGameAppDomain"
            lifestyle="PerWebRequest">
            <parameters>
                 <connectionString>Data Source=ZOLIQ-PC\SQLEXPRESS;Initial Catalog=Gomoku;Integrated Security=True</connectionString>
            </parameters>
    </component>
</castle>
...

I would like to use something like this:

var container =
    new WindsorContainer (new XmlInterpreter (new ConfigResource ("castle")));

gameRepository = container.Resolve (typeof (IGameRepository)) as IGameRepository;

How could I resolve this? Thanks in advance.

回答1:

Just for the sake of completeness, the whole code looks like this:

var container = new WindsorContainer();
container.Install(Castle.Windsor.Installer.Configuration.FromAppConfig());
var gameRepository = container.Resolve<IGameRepository>();

Happy coding.



回答2:

container.Install(Configuration.FromAppConfig());