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

 

转载于:https://www.cnblogs.com/joyet-john/p/7240567.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值