我在MVC中使用Castle.Windsor是这样用的。
首先在UI层安装Install Castle.Windsor
在App_Start中增加一个类WindsorActivator,用于注册和销毁Containter。注意,这里是在PreApplicationStartMethod中注册的,是在ApplicationShutdownMethod中销毁的。
using Castle.Windsor; using Castle.Windsor.Installer; using System; using WebActivatorEx; [assembly: PreApplicationStartMethod(typeof(TaskManagement.UI.App_Start.WindsorActivator), "PreStart")] [assembly: ApplicationShutdownMethodAttribute(typeof(TaskManagement.UI.App_Start.WindsorActivator), "Shutdown")] namespace TaskManagement.UI.App_Start { public static class WindsorActivator { public static IWindsorContainer Container; public static void PreStart() { //将这个Assembly中所有实现IWindsorInstaller接口的类都注册 Container = new WindsorContainer().Install(FromAssembly.This()); } public static void Shutdown() { if (Container != null) Container.Dispose(); } } }