c# castle.window ioc

1.注意的是配置文件"configSections"节点中不能有同级节点。

封装代码如下:

using Castle.MicroKernel;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Castle.Windsor.Installer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Da.Extend
{
    public class CastleContainer
    {
        private static readonly object _locker = new object();
        private static CastleContainer _instance;
        private static IKernel _kernel;

        private CastleContainer()
        {
            Castle.Core.Resource.ConfigResource source = new Castle.Core.Resource.ConfigResource("castle");
            XmlInterpreter interpreter = new XmlInterpreter(source);
            IWindsorContainer windsor= new WindsorContainer(interpreter);
            _kernel = windsor.Kernel;
        }

        public static CastleContainer CreateInstance()
        {
            if (_instance == null)
            {
                lock (_locker)
                {
                    if (_instance == null)
                    {
                        _instance = new CastleContainer();
                    }
                }
            }
            return _instance;
        }

        public T Resolve<T>()
        {
            return _kernel.Resolve<T>();
        }


    }
}

配置文件:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,Castle.Windsor"/>
  </configSections>
  <castle>
    <components>
      <component   id="IUserDao"   service="Da.Dao.IUserDao,Da.Dao"   type="Da.Dao.UserDao,Da.Dao" />
    </components>
  </castle>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>

调用代码:

var userService = new UserService();
            userService.usrDao = CastleContainer.CreateInstance().Resolve<IUserDao>();
            userService.Add(10);

 

posted on 2017-07-26 16:49  伈隨夢飛  阅读(892)  评论(0编辑  收藏  举报

导航