Sample ASP. net mvc project: Suteki. Shop

Source: Internet
Author: User

In this ASP. net mvc example: In Suteki. Shop, Microsoft's own Unity Framework is not used to implement IOC, but the famous Castle Windsor is used. It is necessary to give a brief introduction to the reference of Windsor. In my understanding, this IOC Container includes the following important concepts:

Container iner INER ):Windsor is a reverse control container. It is created on the basis of a microkernel.

The core can scan the class and try to find the object references and object dependencies used by the class, and then provide the dependency information to the class.

Component ):This is what we usually call the business logic unit and the corresponding function implementation. The component is a repeatable

The unit of code used. It should be implemented and exposed as a service. A component is a class that implements a service or interface.

Service ):That is, the corresponding Component interface or the business logic interface composed of N components based on the business logic.

An interface is a service specification. It creates an abstraction layer, and you can easily replace the Service implementation.

Expansion unit plug-in Facilities ):Provides Scalable) containers to manage components.

We can directly use the component as mentioned in the following content), or convert the component into a corresponding service interface for use.

Do you still remember the Service mentioned in the previous article? To put it bluntly, it is a service. Suteki. Shop is more exaggerated. If functional code with business logic can all be regarded as Component or service, such as Filter and ModelBinder mentioned in previous articles. Even the auxiliary class WindsorServiceLocator initialized by the service component is also won.

For ease of understanding, we will go to Suteki. Shop to see how it works.

First, let's take a look at the whole Suteki. Shop project startup portal, which is also the starting point for the Windsor IOC container initialization. This functional code is implemented in the Application_Start method in Global. asaxSuteki. Shop \ Global. asax). The following is the declaration of this method:

ASP. net mvc sample code

 
 
  1. protected void Application_Start(object sender, EventArgs e)  
  2. {  
  3.     RouteManager.RegisterRoutes(RouteTable.Routes);  
  4.     InitializeWindsor();  
  5. }  

In the code, RouteManager. RegisterRoutes is used to bind a Route rule, and the content of the rule is hardcoded into RouteManager. There are a lot of information about Route on the Internet, and many friends in the garden have written it. I will not explain it here.

The above method will run InitializeWindsor (). This is the method used to initialize the Windsor container:

ASP. net mvc sample code

 
 
  1. /// < summary>  
  2. /// This web application uses the Castle Project's IoC container, Windsor see:  
  3. /// http://www.castleproject.org/container/index.html  
  4. /// < /summary>  
  5. protected virtual void InitializeWindsor()  
  6. {  
  7.     if (container == null)  
  8.     {  
  9.         // create a new Windsor Container  
  10.         container = ContainerBuilder.Build("Configuration\\Windsor.config");   
  11.  
  12.         WcfConfiguration.ConfigureContainer(container);  
  13.  
  14.         ServiceLocator.SetLocatorProvider(() => container.Resolve< IServiceLocator>());  
  15.         // set the controller factory to the Windsor controller factory (in MVC Contrib)  
  16.         System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));  
  17.     }  
  18. }  
  19.  

Note: The content in "Configuration \ Windsor. config" is long, mainly for some XML Configuration nodes. You can take the time to read it.

This method is the main content explained today. The following describes the code.

First, determine whether the containerIWindsorContainer type is empty. If the container is empty, create and initialize the container. That is, call the Build method of the ContainerBuilderSuteki. Shop \ ContainerBuilder class to load the default information from the external config file. Let's take a look at the implementation of the Build method:

Sample ASP. net mvc code:

 
 
  1. public static IWindsorContainer Build(string configPath)  
  2. {  
  3.         var container = new WindsorContainer(new XmlInterpreter(configPath));  
  4.  
  5.         // register handler selectors  
  6.         container.Kernel.AddHandlerSelector(new UrlBasedComponentSelector(  
  7.             typeof(IBaseControllerService),  
  8.             typeof(IImageFileService),  
  9.             typeof(IConnectionStringProvider)  
  10.             ));  
  11.  
  12.         // automatically register controllers  
  13.         container.Register(AllTypes  
  14.             .Of< Controller>()  
  15.             .FromAssembly(Assembly.GetExecutingAssembly())  
  16.             .Configure(c => c.LifeStyle.Transient.Named(c.Implementation.Name.ToLower())));  
  17.  
  18.         container.Register(  
  19.             Component.For< IUnitOfWorkManager>().ImplementedBy< LinqToSqlUnitOfWorkManager>().LifeStyle.Transient,  
  20.             Component.For< IFormsAuthentication>().ImplementedBy< FormsAuthenticationWrapper>(),  
  21.             Component.For< IServiceLocator>().Instance(new WindsorServiceLocator(container)),  
  22.             Component.For< AuthenticateFilter>().LifeStyle.Transient,  
  23.             Component.For< UnitOfWorkFilter>().LifeStyle.Transient,  
  24.             Component.For< DataBinder>().LifeStyle.Transient,  
  25.             Component.For< LoadUsingFilter>().LifeStyle.Transient,  
  26.             Component.For< CurrentBasketBinder>().LifeStyle.Transient,  
  27.             Component.For< ProductBinder>().LifeStyle.Transient,  
  28.             Component.For< OrderBinder>().LifeStyle.Transient,  
  29.             Component.For< IOrderSearchService>().ImplementedBy< OrderSearchService>().LifeStyle.Transient,  
  30.             Component.For< IEmailBuilder>().ImplementedBy< EmailBuilder>().LifeStyle.Singleton  
  31.         );  
  32.  
  33.         return container;  
  34. }  
  35.  

First, read the XML node information of the specified configuration file, construct a WindsorContainer implementation, and add the "container processing component" method AddHandlerSelector in its microkernel ), note that this processing method is handled as defined in the business logic.

The Controller is registered with the container, and the LifeStyle of the Configuration Attribute is specified as the Transient type. It is necessary to introduce the component life cycle of the Castle container, including the following:

Singleton: only one instance in the container will be created

Transient: each request creates a new instance

PerThread: only one instance exists in each thread.

PerWebRequest: each time a web Request creates a new instance

Pooled: You can use the "Pooled" method to manage components. You can use the PooledWithSize method to set related attributes of the pool.

In this project, the life cycle of the component is basically designated as the Transient type, that is, when a request is created, it is destroyed after processing.

Next, let's take a look at the remaining code of this method, that is, register the components of the business logic such as ModelBinder, Filter, and Service. At the same time, we can see that some group classes are bound to the default implementation classes while performing interface registration. This hard encoding method is an "optional" method.

Before completing the Build method, return to the InitializeWindsor method in the Global. asax file and check the remaining code. We can see this line:

 
 
  1. WcfConfiguration.ConfigureContainer(container);  

The ConfigureContainer method of WcfConfiguration class is to add components to the currently created container. The component to be added this time is the IMetaWeblog interface implementation class of Windows Live Writer, as follows:

 
 
  1. public static class WcfConfiguration  
  2. {  
  3.     public static void ConfigureContainer(IWindsorContainer container)  
  4.     {  
  5.         var returnFaults = new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true };  
  6.  
  7.         container.AddFacility< WcfFacility>(f =>  
  8.         {  
  9.             f.Services.AspNetCompatibility = AspNetCompatibilityRequirementsMode.Required;  
  10.             f.DefaultBinding = new XmlRpcHttpBinding();  
  11.         })  
  12.             .Register(  
  13.                 Component.For< IServiceBehavior>().Instance(returnFaults),  
  14.                 Component.For< XmlRpcEndpointBehavior>(),  
  15.                 Component.For< IMetaWeblog>().ImplementedBy< MetaWeblogWcf>().Named("metaWebLog").LifeStyle.Transient  
  16.                 );  
  17.  
  18.     }  
  19. }  
  20.  

As mentioned above, the expansion unit plug-in Facilities can inject the function code you need without changing the original components, the AddFacility method is used to add extension units to register and manage our Windows Live Writer components.

Next we will analyze the remaining code in the InitializeWindsor method, read the ConfigureContainer method, and then we will see the following line of code:

 
 
  1. ServiceLocator.SetLocatorProvider(() => container.Resolve< IServiceLocator>()); 

I was familiar with seeing this line. I remember reading this line of code similar to this in Oxite's Global. asax.

 
 
  1. ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));   

But that project uses Unity instead of Castle Windsor. However, the actual functions are the same. Resolve and bind the service address in the container. With this feature, you can use the methods defined in Microsoft. Practices. ServiceLocation. ServiceLocatorImplBase, such as DoGetInstance or DoGetAllInstances, to obtain the corresponding service component set.

For example, the implementation code of DoGetInstance and DoGetAllInstances () in this project is as follows:

Sample Code of ASP. net mvc: Suteki. Common \ Windsor \ WindsorServiceLocator. cs ):

 
 
  1. protected override object DoGetInstance(Type serviceType, string key)  
  2. {  
  3.     if (key != null)  
  4.         return container.Resolve(key, serviceType);  
  5.     return container.Resolve(serviceType);  
  6. }  
  7.  
  8. /// < summary>  
  9. /// When implemented by inheriting classes, this method will do the actual work of  
  10. /// resolving all the requested service instances.  
  11. /// < /summary>  
  12. /// < param name="serviceType">Type of service requested.< /param>  
  13. /// < returns>  
  14. /// Sequence of service instance objects.  
  15. /// < /returns>  
  16. protected override IEnumerable< object> DoGetAllInstances(Type serviceType)  
  17. {  
  18.     return (object[])container.ResolveAll(serviceType);  
  19. }  
  20.  

Note: The IOC of the WindsorServiceLocator class is bound to ContainerBuilder. Build,As follows:

 
 
  1. container.Register(  
  2.        Component.For< IUnitOfWorkManager>().ImplementedBy< LinqToSqlUnitOfWorkManager>().LifeStyle.Transient,  
  3.        Component.For< IFormsAuthentication>().ImplementedBy< FormsAuthenticationWrapper>(),  
  4.        Component.For< IServiceLocator>().Instance(new WindsorServiceLocator(container)),  

The last line of code in the InitializeWindsor method is as follows:

 
 
  1. System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));  

The WindsorControllerFactory class is provided in the MvcContrib project to construct a Controller factory of the Castle project type.

  1. ASP. NET shutdown code (Windows is the local machine)
  2. ASP. NET QueryString garbled Solution
  3. ASP. NET screen jump implementation and value passing Solution
  4. ASP. NET Web application user operation Information Description class
  5. The father of ASP. NET is strongly recommended: ASP. NET AJAX

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.