Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

ASP.NET MVC sample project analysis

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "ASP.NET MVC sample project analysis", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "ASP.NET MVC sample project analysis" bar!

In this ASP.NET MVC example: Suteki.Shop, instead of using Microsoft's own Unity framework to implement IOC, it uses the famous Castle Windsor. Because Windsor is referenced, it is necessary to give a brief introduction. As far as I understand, this IOC container (Container) includes the following important concepts:

Container (Container): Windsor is a reverse control container. It is created on the basis of a microkernel, this microkernel.

The kernel can scan classes and try to find out which object references and object dependencies are used by these classes, and then provide these dependency information to the class.

Component (Component): that is, what we usually call a business logic unit and the corresponding functional implementation, a 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 (Service): that is, the corresponding component interface or the business logic interface composed of N Component according to business logic.

An interface is the specification of a service that creates an abstraction layer where you can easily replace the implementation of the service.

Expansion Unit plug-in (Facilities): provides (expandable) containers to manage components.

We can use the component directly (mentioned below), or we can convert the component to the corresponding service interface to use.

Remember the Service mentioned in the last article? To put it bluntly, it is a service. On the other hand, Suteki.Shop is more "exaggerated". Functional code with a business logic nature can be regarded as a Component or a service, such as Filter,ModelBinder mentioned in previous articles. Even the helper class (WindsorServiceLocator) initialized by the service component is also taken down.

To make it easier to understand, let's take a look at how it is done in Suteki.Shop

First of all, let's take a look at the entry point where the entire Suteki.Shop project starts, which is also the starting point for initializing the Windsor IOC container. This functional code is implemented in the Application_Start method in Global.asax (Suteki.Shop\ Global.asax). The following is the declaration of the method:

ASP.NET MVC sample code

Protected void Application_Start (object sender, EventArgs e) {RouteManager.RegisterRoutes (RouteTable.Routes); InitializeWindsor ();}

The RouteManager.RegisterRoutes in the code implements the binding to the Route rules, and the contents of the rules are hard-coded into RouteManager. There are a lot of information about Route online, and many friends in the garden have written about it, so I won't explain it here.

Then the above method runs InitializeWindsor (), which is how the Windsor container initializes:

ASP.NET MVC sample code

/ / /

< summary>

/ This web application uses the Castle Project's IoC container, Windsor see: / http://www.castleproject.org/container/index.html /

< /summary>

Protected virtual void InitializeWindsor () {if (container = = null) {/ / create a new Windsor Container container = ContainerBuilder.Build ("Configuration\\ Windsor.config"); WcfConfiguration.ConfigureContainer (container); ServiceLocator.SetLocatorProvider (() = > container.Resolve

< IServiceLocator>

(); / / set the controller factory to the Windsor controller factory (in MVC Contrib) System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory (new WindsorControllerFactory (container));}}

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

This method is the main content of today's explanation, let's introduce the code in it.

The first step is to determine whether the container (IWindsorContainer type) is empty, and if the container is empty, create and initialize the container. That is, call the Build method of the ContainerBuilder (Suteki.Shop\ ContainerBuilder) class to load the default information from an external config file. Let's take a look at the implementation of the Build method:

ASP.NET MVC sample code:

Public static IWindsorContainer Build (string configPath) {var container = new WindsorContainer (new XmlInterpreter (configPath)); / / register handler selectors container.Kernel.AddHandlerSelector (new UrlBasedComponentSelector (typeof (IBaseControllerService), typeof (IImageFileService), typeof (IConnectionStringProvider)); / / automatically register controllers container.Register (AllTypes. Of)

< Controller>

() .FromAssembly (Assembly.GetExecutingAssembly ()) .configure (c = > c.LifeStyle.Transient.Named (c.Implementation.Name.ToLower (); container.Register (Component.For)

< IUnitOfWorkManager>

() ImplementedBy

< LinqToSqlUnitOfWorkManager>

() LifeStyle.Transient, Component.For

< IFormsAuthentication>

() ImplementedBy

< FormsAuthenticationWrapper>

(), Component.For

< IServiceLocator>

Instance (new WindsorServiceLocator (container)), Component.For

< AuthenticateFilter>

() LifeStyle.Transient, Component.For

< UnitOfWorkFilter>

() LifeStyle.Transient, Component.For

< DataBinder>

() LifeStyle.Transient, Component.For

< LoadUsingFilter>

() LifeStyle.Transient, Component.For

< CurrentBasketBinder>

() LifeStyle.Transient, Component.For

< ProductBinder>

() LifeStyle.Transient, Component.For

< OrderBinder>

() LifeStyle.Transient, Component.For

< IOrderSearchService>

() ImplementedBy

< OrderSearchService>

() LifeStyle.Transient, Component.For

< IEmailBuilder>

() ImplementedBy

< EmailBuilder>

(). LifeStyle.Singleton); return container;}

The first step is to read in the XML node information of the specified configuration file, construct a WindsorContainer implementation, and add a "container processing component" (AddHandlerSelector) to its microkernel, noting that this processing is handled in the way we specify in the business logic.

Then 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, mainly as follows:

Singleton: only one instance in the container will be created

Transient: create a new instance for each request

PerThread: there is only one instance per thread

PerWebRequest: create a new instance for each web request

Pooled: components are managed in a "pooled" manner, and the relevant properties of the pool can be set using the PooledWithSize method.

You can see that in this project, the life cycle of the component is basically specified as the Transient type, that is, it is created when the request occurs and destroyed after processing.

Then take a look at the rest of the code for this method, that is, registering components of business logic such as ModelBinder,Filter,Service. At the same time, we see that some group classes are bound to the default implementation class while registering the interface, and this hard-coding method is an "optional" way.

Before you finish talking about the Build method, go back to the InitializeWindsor method in the Global.asax file and take a look at the rest of the code. We see this line:

WcfConfiguration.ConfigureContainer (container)

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

Public static class WcfConfiguration {public static void ConfigureContainer (IWindsorContainer container) {var returnFaults = new ServiceDebugBehavior {IncludeExceptionDetailInFaults = true}; container.AddFacility

< WcfFacility>

(F = > {f.Services.AspNetCompatibility = AspNetCompatibilityRequirementsMode.Required; f.DefaultBinding = new XmlRpcHttpBinding ();}) .Register (Component.For

< IServiceBehavior>

() Instance (returnFaults), Component.For

< XmlRpcEndpointBehavior>

(), Component.For

< IMetaWeblog>

() ImplementedBy

< MetaWeblogWcf>

(). Named ("metaWebLog") .LifeStyle.Transient);}}

As mentioned earlier, the extension unit plug-in (Facilities) can inject the functional code you need without changing the original components, so here we use its AddFacility method to add extension units to register and manage our Windows Live Writer components.

After analyzing the rest of the code in the InitializeWindsor method, and after looking at the ConfigureContainer method, this is the following line of code:

ServiceLocator.SetLocatorProvider () = > container.Resolve

< IServiceLocator>

())

Just seeing this line makes me feel deja vu. I remember seeing a similar line of code in the Global.asax of watching Oxite before.

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

It's just that Unity was used instead of Castle Windsor in that project. But the actual function is the same. That is, the resolution and binding of the service address in the container is completed. With it, you can obtain an instance of the corresponding service component (collection) through the methods defined in Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase, such as DoGetInstance or DoGetAllInstances.

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

(ASP.NET MVC sample code: Suteki.Common\ Windsor\ WindsorServiceLocator.cs):

Protected override object DoGetInstance (Type serviceType, string key) {if (key! = null) return container.Resolve (key, serviceType); return container.Resolve (serviceType);} / /

< summary>

/ When implemented by inheriting classes, this method will do the actual work of / resolving all the requested service instances. / / /

< /summary>

/ / /

< param name="serviceType">

Type of service requested.

< /param>

/ / /

< returns>

/ Sequence of service instance objects. / / /

< /returns>

Protected override IEnumerable

< object>

DoGetAllInstances (Type serviceType) {return (object []) container.ResolveAll (serviceType);}

Note that the IOC for this WindsorServiceLocator class is bound in ContainerBuilder.Build, as follows:

Container.Register (Component.For

< IUnitOfWorkManager>

() ImplementedBy

< LinqToSqlUnitOfWorkManager>

() LifeStyle.Transient, Component.For

< IFormsAuthentication>

() ImplementedBy

< FormsAuthenticationWrapper>

(), Component.For

< IServiceLocator>

(). Instance (new WindsorServiceLocator (container))

The * line in the InitializeWindsor method is as follows:

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

What is explained here is that the WindsorControllerFactory class is provided in the MvcContrib project and is used to construct a Controller factory of Castle project type.

Thank you for your reading, the above is the content of "ASP.NET MVC sample project analysis", after the study of this article, I believe you have a deeper understanding of the ASP.NET MVC sample project analysis, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report