Castle IOC for MVC use method

Source: Internet
Author: User

Castle Web.api How to use

First, create windsoractivator inherit Ihttpcontrolleractivator

 public class Windsoractivator:ihttpcontrolleractivator {private readonly IWindsorContainer container;        Public windsoractivator (IWindsorContainer container) {This.container = container; } public Ihttpcontroller Create (httprequestmessage request, Httpcontrollerdescriptor control Lerdescriptor, Type controllertype) {var controller = (Ihttpcontroller) this.c Ontainer.            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 (); }        }

Second, create  dependencyinstaller 

public class Dependencyinstaller:iwindsorinstaller {public void Install (IWindsorContainer container, Iconfigu Rationstore 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 ()); }    }

Three, add the following code in the Global code file, you can

   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 Injection Package GlobalConfiguration.Configuration.ServiCes.            Replace (typeof (Ihttpcontrolleractivator), New Windsoractivator (This.container));            Controller injection Package var controllerfactory = new WindsorControllerFactory (Containerbycon.kernel);        ControllerBuilder.Current.SetControllerFactory (controllerfactory); }

How to use Castle MVC

First, the basic method ibid, but there are differences, WEB.API is implemented by Apicontroller, using Ihttpcontroller but MVC uses icontroller, so we will create a icontroller for the injection port WindsorControllerFactory

 Public classWindsorcontrollerfactory:defaultcontrollerfactory {Private ReadOnlyIkernel kernel;  Publicwindsorcontrollerfactory (Ikernel kernel) { This. Kernel =kernel; }         Public Override voidReleasecontroller (IController Controller) {kernel.        Releasecomponent (Controller); }        protected OverrideIController getcontrollerinstance (RequestContext requestcontext, Type controllertype) {if(Controllertype = =NULL)            {                Throw NewHttpException (404,string. Format ("The controller for path ' {0} ' is could not being found.", RequestContext.HttpContext.Request.Path)); }            return(IController) kernel.        Resolve (Controllertype); }    }

Second, then add the following code to "global" can, like a global, the code is all posted out.

var New windsorcontrollerfactory (containerbycon.kernel);            ControllerBuilder.Current.SetControllerFactory (controllerfactory);

This is done, can be used directly, the use of the following examples:

Web. API Usage Examples:

  Public classUserinfocontroller:apicontroller {iuserinfoservice iuserinfoservice;        Ilogservice Ilogservice;  PublicUserinfocontroller (Iuserinfoservice iuserinfoservice, Ilogservice ilogservice) { This. Iuserinfoservice =Iuserinfoservice;  This. Ilogservice =Ilogservice; } [Enablecors] PublicIqueryable<userinfo>getuserinfolist () {IQueryable<UserInfo>uiflist; Uiflist=iuserinfoservice.getuserinfolist (); returnUiflist;
...........................

MVC usage Examples

  Public classOauthcontroller:controller {iuserinfoservice iuserinfoservice;        Ilogservice Ilogservice;  PublicOauthcontroller (Iuserinfoservice _iuserinfoservice, Ilogservice _ilogservice) { This. Iuserinfoservice =_iuserinfoservice;  This. Ilogservice =_ilogservice; }         PublicActionResult Index (stringcode) {Chatusermodel Chum=NewChatusermodel (); if(Code! =NULL& Code! ="") {Chatuser chu=NewChatuser (); Chum=Chu.                Getchatuser (code); UserInfo NewUser=NewUserInfo (); NewUser. City=chum.city;NewUser. Updatatime=System.DateTime.Now; NewUser. Remark="User Bindings"; intstates =iuserinfoservice.insertuserinof (NewUser); Ilogservice.logger (). Info (string. Format ("Add new user by {0} in {1}", NewUser. Nickname, NewUser.            Updatatime));                 ...............................

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.