c# Castle Windsor简单例子

Windsor是Castle的IOC框架。需要用到两个dll(Castle.Core.dll和Castle.Windsor.dll)。

1、接口以及接口实现类:

public interface ITest
    {
        int Add(int a, int b);
    }
 public class Test:ITest
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

2、创建自定义类WindsorInstaller,继承IWindsorInstaller,实现IWindsorInstaller的Install方法,如下:

public class WindsorInstaller: IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            //单个注册法,还有其他方式
            //ITest为接口,Test为接口的实现类
            container.Register(Component.For<ITest>().ImplementedBy<Test>());
        }
    }

3、创建自定义类WindsorInit,单例模式获取ioc容器:

 public class WindsorInit
    {
        private static WindsorContainer _container;
        public static WindsorContainer GetContainer()
        {
            if (_container == null)
            {
                _container = new WindsorContainer();
                _container.Install(FromAssembly.This());
            }
            return _container;
        }

        public void CloseContex()
        {
            _container.Dispose();
        }
    }

4、mvc中controller中使用:

public class HomeController : Controller
    {
        private ITest _test;
        public ActionResult Index()
        {
            WindsorContainer container = WindsorInit.GetContainer();
            _test = container.Resolve<ITest>(new Arguments(new { }));
            var result = _test.Add(10,20);
            ViewBag.result = result;
            return View();
        }
    }

页面会输出结果:30

 

这里简单实现Castle Windsor(IOC)。

 

posted @ 2018-05-12 12:01  一夜秋2014  Views(2934)  Comments(0Edit  收藏  举报