How to instantiate a class based on web.config file with Castle Windsor?

谁说胖子不能爱 提交于 2019-12-11 03:17:09

问题


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());


来源:https://stackoverflow.com/questions/5565868/how-to-instantiate-a-class-based-on-web-config-file-with-castle-windsor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!