Using structuremap with the ASP. net mvc Framework

Source: Internet
Author: User

Address: http://www.bengtbe.com/blog/post/2009/02/27/Using-StructureMap-with-the-ASPNET-MVC-framework.aspx

Using structuremap with the ASP. net mvc Framework

Friday Author: bengtbe

Here I want to explain how to use the structuremap class under the. NET frameword framework.
You need to have a basic understanding of ASP. net mvc Framework, dependency injection, and control inversion.
These technologies are not only used for structuremap. If you like these technologies, you can also use other di/IOC tools.

Let's talk about this usercontroller example. It has an iuserservice attribute to call the service at the control layer. When

Iuserservice itself also calls the iuserpepository method at the data layer. Use this usercontroller

Control reverse conversion to access iuserservice, which means that this userservice class selects control reverse conversion for injection.

Usercontroller instantiate iuserservice;
Public class usercontroller: Controller
{
Private readonly iuserservice m_userservice;
Public usercontroller (iuserservice userservice)
{
M_userservice = userservice;
}
Public actionresult edit (int id)
{
Return view (m_userservice.getbyid (ID ));
}
}
This is called container injection. If you write this code without writing other configuration files, you will get the following error:
Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
No parameterless constructor defined for this object.

Description: An unhandled exception occurred during the execution of the current web

Request. Please review the stack trace for more information about the error and where

It originated in the code.

Exception details: system. missingmethodexception: No parameterless constructor defined

For this object.
Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
In fact, by default, this ASP. net mvc Framework requires a constructor. One method is the following constructor:
Public usercontroller (): This (New userservice (New userrepository ()))
{
}
The above code is constructed by calling this method during runtime. To solve the error, you can rewrite this constructor.

It is called poor man's dependency injection (the second method that unknown wise person chooses). If you know DI/IOC, you will select another one.

.
The above method also has a major drawback (I have a deep understanding of this ^ _ ^), that is, it is used when you write this interface to death.

Userservice initializes iuserservice. Similarly, you may use the same method to process

Userrepository. In this way, the view layer is associated with the data layer. At this time, if userrepository has several more attributes

It seems that writing code is ugly...

Let's use the objectfactory of structuremap to achieve the same effect. (Initialization

Iuserservice) code:
Public usercontroller (): This (objectfactory. getinstance <iuserservice> ())
{
}
Simple code! In this way, this attribute is initialized. However, every controller must do this to achieve the effect.

Is there no simpler way? Let's simplify it as much as possible.
ASP. net mvc framework uses this factory parameter to initialize controllers and provides a base class
Defaultcontrollerfactory allows you to initialize controller more freely:
Public class structuremapcontrollerfactory: defaultcontrollerfactory
{
Protected override icontroller getcontrollerinstance (type controllertype)
{
If (controllertype = NULL) return NULL;
Try
{
Return objectfactory. getinstance (controllertype) as controller;
}
Catch (structuremapexception)
{
System. Diagnostics. Debug. writeline (objectfactory. whatdoihave ());
Throw;
}
}
}
This method is called every time we call the controller. The above code is
The process of customizing the controller through objectfactory is automatically initialized even if there is no interface in your class.

All such interface attributes;
Now I will tell you how to add this code to global. asax. CS and load it when the program runs. As follows:
Protected void application_start ()
{
Registerroutes (routetable. routes );
Structuremapconfiguration. Configure ();
Controllerbuilder. Current. setcontrollerfactory (New
Structuremapcontrollerfactory ());
}
The last line tells the framework to use our customized factory instead of the default one. Now you can

Initialize the parameter last year. Let struturemap help you.

Struturemap Construction
Do you see the second line of the above Code? It is used to construct struturemap. It will build a new struturemap not

XML is required for configuration.
Public class structuremapconfiguration
{
Public static void configure ()
{
Objectfactory. initialize (initializestructuremap );
}
Private Static void initializestructuremap (iinitializationexpression X)
{
X. Scan (y =>
{
Y. Assembly ("mvcwithnhib.pdf. repositories ");
Y. Assembly ("mvcwithnhib.pdf. services ");
Y. With <defaconconventionmessages> ();
}
);

Http://stackoverflow.com/questions/1183124/how-do-i-mock-httpresponsebase-end

}
}
You can learn how to use defaultconventionscanner. This token is used to record which interfaces correspond to which classes.

. For example, userservice is used to initialize iuserservice and userrepository.

Iuserrepository.
Summary:
Here we will introduce how to use structuremap under the framework of ASP. net mvc framework.

Controller factory to simplify your code. Generally, at the beginning, objectfactory is used

Method can reduce a lot of code. Here we only introduce the application of objectfactory in the Controller layer (other places can also

);

I also wrote some code and introduced some common applications.

Interface and class ing can be controlled)

 

(I have tried this very well. I also found that if the class constructor has an interface, it will initially become the registration method and will give priority to the initialization of the interface. But I didn't try it. What should I do if there are more than two parameters? I think the initialization should be based on the one with the most parameters! You have not tried it. If you have time, try it .)

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.