Castle IOC FOR MVC 使用方法
Castle Web.API 使用方法
一、创建 WindsorActivator 继承 IHttpControllerActivator
public class WindsorActivator :IHttpControllerActivator { private readonly IWindsorContainer container; public WindsorActivator(IWindsorContainer container) { this.container = container; } public IHttpController Create( HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) { var controller = (IHttpController)this.container.Resolve(controllerType); request.RegisterForDispose( new Release( () => this.container.Release(controller))); return controller; } public IController Create(RequestContext requestContext, Type controllerType) { var controller = (IController)this.container.Resolve(controllerType); return controller; } private class Release : IDisposable { private readonly Action release; public Release(Action release) { this.release = release; } public void Dispose() { this.release(); } }
二、创建 DependencyInstaller
public class DependencyInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For<ILogService>() .ImplementedBy<LogService>() .LifeStyle.PerWebRequest, Component.For<IDatabaseFactory>() .ImplementedBy<DatabaseFactory>() .LifeStyle.PerWebRequest, Component.For<IUnitOfWork>() .ImplementedBy<UnitOfWork>() .LifeStyle.PerWebRequest, AllTypes.FromThisAssembly().BasedOn<IHttpController>().LifestyleTransient(), AllTypes.FromThisAssembly().BasedOn<IController>().LifestyleTransient(), AllTypes.FromAssemblyNamed("WebChat.Service") .Where(type => type.Name.EndsWith("Service")).WithServiceAllInterfaces().LifestylePerWebRequest(), AllTypes.FromAssemblyNamed("WebChat.Repository") .Where(type => type.Name.EndsWith("Repository")).WithServiceAllInterfaces().LifestylePerWebRequest() ); } }
三、在全局代码文件中加入以下代码,就可以了
public class WebApiApplication : System.Web.HttpApplication { private readonly IWindsorContainer container; private readonly IWindsorContainer containerByCon; public WebApiApplication() { this.container = new WindsorContainer().Install(new DependencyInstaller()); this.containerByCon = new WindsorContainer().Install(new DependencyInstaller()); } public override void Dispose() { this.container.Dispose(); this.containerByCon.Dispose(); base.Dispose(); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //API注入包 GlobalConfiguration.Configuration.Services.Replace( typeof(IHttpControllerActivator), new WindsorActivator(this.container)); //controller 注入包 var controllerFactory = new WindsorControllerFactory(containerByCon.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory); }
Castle mvc 使用方法
一、基本方法同上,但也有区别,Web.api 是由apicontroller来实现的,使用的是 IHttpController 但MVC 使用的是IController ,所以我们要次创建一个针对IController 的注入口 WindsorControllerFactory
public class WindsorControllerFactory : DefaultControllerFactory { private readonly IKernel kernel; public WindsorControllerFactory(IKernel kernel) { this.kernel = kernel; } public override void ReleaseController(IController controller) { kernel.ReleaseComponent(controller); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path)); } return (IController)kernel.Resolve(controllerType); } }
二、然后在“Global”中加入以下代码就可以,如上图个那个 Global 一样的,代码已全部贴出来了。
var controllerFactory = new WindsorControllerFactory(containerByCon.Kernel); ControllerBuilder.Current.SetControllerFactory(controllerFactory);
这样就完成了,可以直接的使用了,使用实例如下:
WEB.API 使用实例:
public class UserInfoController : ApiController { IUserInfoService iuserInfoService; ILogService ilogService; public UserInfoController(IUserInfoService iuserInfoService, ILogService ilogService) { this.iuserInfoService = iuserInfoService; this.ilogService = ilogService; } [EnableCors] public IQueryable<UserInfo> GetUserInfoList() { IQueryable<UserInfo> uifList; uifList = iuserInfoService.GetUserInfoList(); return uifList;
...........................
MVC 使用实例
public class OAuthController : Controller { IUserInfoService iuserInfoService; ILogService ilogService; public OAuthController(IUserInfoService _iuserInfoService, ILogService _ilogService) { this.iuserInfoService = _iuserInfoService; this.ilogService = _ilogService; } public ActionResult Index(string code) { ChatUserModel chum = new ChatUserModel(); if (code != null & code != "") { ChatUser chu = new ChatUser(); chum = chu.GetChatUser(code); UserInfo newuser = new UserInfo(); newuser.City = chum.city; newuser.UpdataTime = System.DateTime.Now; newuser.Remark = "用户绑定"; int states = iuserInfoService.InsertUserInof(newuser); ilogService.Logger().Info(string.Format("add new user by {0} in {1}", newuser.NickName, newuser.UpdataTime)); ...............................
激情燃烧