ASP. NET MVC3 makes dependency injection simpler (the Ninject example is added)

Source: Internet
Author: User

Links: http://www.cnblogs.com/cnmaxu/archive/2010/10/13/1849972.html

Yesterday, I wrote an article (see ASP. net mvc dependency injection). I personally feel that this implementation method is not so smooth. While writing it out and sharing it with everyone,

I also want to give you some suggestions. Today I downloaded the latest ASP. NET MVC3 Beta version released by Microsoft, and carefully read its Release Notes,

I was pleasantly surprised that MVC3 added support for dependency injection and added an IDependencyResolver interface definition, which is really good and much smoother than my original implementation,

It's still the old method. I went to the blog of the Microsoft bulls to check if there was any written code. If there was any, I could use it. If not, I could only write it myself. As a result, I was very disappointed, or maybe I am too stupid,

I didn't find a complete example. I only found some code snippets. So I sorted them out and shared them with you,

If you are an expert, please do not hesitate to give us some advice. The following is a code snippet.

1. Implement the code of the dependency Injection Interface IDependencyResolver and MyDependencyResolver. cs provided in MVC3 Beta:

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Mvc;
Using Microsoft. Practices. Unity;
Namespace Demo
{
Public class MyDependencyResolver: IDependencyResolver
{
# Region IDependencyResolver Member
/// <Summary>
/// Dependency injection container
/// </Summary>
Private UnityContainer _ unityContainer;
/// <Summary>
/// Structure
/// </Summary>
/// <Param name = "aUnityContainer"> dependency injection container </param>
Public MyDependencyResolver (UnityContainer aUnityContainer)
{
_ UnityContainer = aUnityContainer;
}
Public object GetService (Type aServiceType)
{
Try
{
Return _ unityContainer. Resolve (aServiceType );
}
Catch
{
/// According to Microsoft's requirements, this method must return null if no object is parsed !!!!
Return null;
}
}
Public IEnumerable <object> GetServices (Type aServiceType)
{
Try
{
Return _ unityContainer. ResolveAll (aServiceType );
}
Catch
{
/// According to Microsoft's requirements, this method must return an empty set if no object is parsed. This must be done !!!!
Return new List <object> ();
}
}
# Endregion
}
}

2. Set the dependency injection parser DependencyResolver in Global. asax. cs (this is a Global static class and also added in MVC3 Beta ):

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Mvc;
Using System. Web. Routing;
Using Microsoft. Practices. Unity;
Namespace Demo
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// Visit http://go.microsoft.com /? LinkId = 9394801
Public class MvcApplication: System. Web. HttpApplication
{
Public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
Filters. Add (new HandleErrorAttribute ());
}
Public static void RegisterRoutes (RouteCollection routes)
{
Routes. IgnoreRoute ("{resource}. axd/{* pathInfo }");
Routes. MapRoute (
"Default", // Route name
"{Controller}/{action}/{id}", // URL with parameters
New {controller = "Home", action = "Index", id = UrlParameter. Optional}
);
}
Protected void Application_Start ()
{
AreaRegistration. RegisterAllAreas ();
RegisterGlobalFilters (GlobalFilters. Filters );
RegisterRoutes (RouteTable. Routes );
// Set dependency Injection
RegisterDependency ();
}
Private static UnityContainer _ Container;
Public static UnityContainer Container
{
Get
{
If (_ Container = null)
{
_ Container = new UnityContainer ();
}
Return _ Container;
}
}
Protected void RegisterDependency ()
{
Container. RegisterType <ITest, Test> ();
DependencyResolver. SetResolver (new MyDependencyResolver (Container ));
}
}
}

3. Controller code, HomeController. cs:

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. Web. Mvc;
Using Microsoft. Practices. Unity;
Namespace Demo. Controllers
{
Public class HomeController: Controller
{
[Dependency]
Public ITest Test {get; set ;}
Public ActionResult Index ()
{
ViewModel. Message = Test. GetString ();
Return View ();
}
Public ActionResult About ()
{
Return View ();
}
}
}

4. ITest. cs code:

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Namespace Demo
{
Public interface ITest
{
String GetString ();
}
}

5. Test. cs code:

Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Namespace Demo
{
Public class Test: ITest
{
# Region ITest Member
Public string GetString ()
{
Return "Run demo! ";
}
# Endregion
}
}

* *** Note: This article is only applicable to ASP. NET MVC3 Beta. It may not be implemented in the official version in the future. After all, for dependency injection,

From MVC1-> MVC3 Preview1-> MVC3 Beta has been changing (Brad Wilson) I also mentioned in my blog that:

Disclause

This blog post talks about ASP. net mvc 3 Beta, which is a pre-release version. Specific technical details may change before the final release of MVC 3.

This release is designed to elicit feedback on features with enough time to make meaningful changes before MVC 3 ships,

So please comment on this blog post or contact me if you have comments.

(See article: http://bradwilson.typepad.com/blog/2010/10/service-location-pt5-idependencyresolver.html)

It's too bad for me to get down to text e. Let's take a look at it for yourself.

Here is a complete example of using the Unity dependency injection framework: Download (Environment: VS2010 + MVC3 Beta + Unity)

Here is a complete example of using the Ninject dependency injection framework: Download (Environment: VS2010 + MVC3 Beta + Ninject)

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.