Use Castle Windsor and mvcwindsor in ASP. NET MVC

Source: Internet
Author: User

Use Castle Windsor and mvcwindsor in ASP. NET MVC

 

Generally, there are many Inject instances. Today, we have access to Castle Windsor. This article describes how to use ASP. net mvc.

 

Visual Studio 2012 creates an ASP. net mvc 4 website.

 

Install Castle Windsor through NuGet.

 

Create a folder named "IOC" under the current project.

 

In ASP. net mvc, every request, DefaultControllerFactory will create a controller instance for us. We need to customize a class derived from DefaultControllerFactory so that Castle Windsor can help us generate a controller instance.

 

using System.Web;
using System.Web.Mvc;
using Castle.MicroKernel;
namespace MyCastleWindsor.IOC
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel _kernel;
        public WindsorControllerFactory(IKernel kernel)
        {
            _kernel = kernel;
        }
        protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, System.Type controllerType)
        {
            if (controllerType == null)
            {
Throw new HttpException (404, string. Format ("the current {0} Request does not exist", requestContext. HttpContext. Request. Path ));
            }
            return (IController)_kernel.Resolve(controllerType);
        }
        public override void ReleaseController(IController controller)
        {
            _kernel.ReleaseComponent(controller);
            base.ReleaseController(controller);
        }
    }
}

 

Now you need to generate the Castle Windsor instance in the global environment, assign the value to the custom ControllerFactory constructor, and destroy the Castle Windsor instance at the end of the Application.

 

   public class MvcApplication : System.Web.HttpApplication
    {
        private IWindsorContainer _container;
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
// Initialize an IOC container
            _container = new WindsorContainer().Install(FromAssembly.This());
// Complete registration in the IWindsorInstaller Interface
            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(_container.Kernel));
        }
        protected void Application_End()
        {
            _container.Dispose();
        }
    }

 

Now, you need to tell Castle Windsor under what conditions and how to register dependencies. Castle Windsor provides the IWindsorInstaller interface. Create a class to implement this interface in the IOC folder.

 

using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using MyCastleWindsor.Controllers;
namespace MyCastleWindsor.IOC
{
    public class ControllerInstaller : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
Container. Register (Classes. FromThisAssembly () // where to find the interface or Class
. BasedOn <IController> () // implements the IController interface.
. If (Component. IsInSameNamespaceAs <HomeController> () // In the same namespace as HomeController
. If (t => t. Name. EndsWith ("Controller") // end with "Controller"
. Configure (c => c. LifestylePerWebRequest (); // each request creates a Controller instance
        }
    }
}

 

In fact, when you run the Install (FromAssembly. This () method in a global file, the Install interface method of IWindsorInstaller is executed.

 

public interface IContactManager
{}

 

Interface implementation class:

 

public class ContactManager : IContactManager
{}

 

In a controller, dependencies are injected through constructor. We hope to write:

 

private IContactManager contactManager;
public HomeController(IContactManager contactManager)
{
    this.contactManager = contactManager;
}

 

Now you need to register IContactManager and ContactManager. You can use reflection to register dependencies.


using System.Web.Mvc;
using Castle.MicroKernel.Registration;
using MyCastleWindsor.Controllers;
namespace MyCastleWindsor.IOC
{
    public class ControllerInstaller : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly()
                .Where(t => t.Name.EndsWith("Manager"))
                .WithServiceDefaultInterfaces()
                .Configure(c => c.LifestyleTransient()));
        }
    }
}

 

The Application of Castle Windsor is roughly as follows:

 

→Inherit the ControllerFactory of ASP. net mvc, and pass in the IKernel of Castle Windsor through the constructor to let it parse the IController type controller.

→ Register dependencies through reflection by implementing the IWindsorInstaller interface of Castle Windsor.

→ Initialize the Castle Windsor instance in the Global File and register the custom ControllerFactory.

Related Article

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.