ASP. net mvc 3.0 Learning Series-Dependency Resolution in ASP. net mvc 3.0

Source: Internet
Author: User

Sorry, we have not updated this series of articles on vacation recently. I originally wanted to write about NuGet first, but I think NuGet does not have to spend too much time for everyone. I 'd like to know about DI in ASP. NET MVC 3 first.

ASP. net mvc 3.0 Learning Series-Preface

ASP. net mvc 3.0 Learning Series -- Razor and ASP. net mvc 3.0

ASP. net mvc 3.0 Learning Series-Controllers in ASP. net mvc 3.0

ASP. net mvc 3.0 Learning Series-Model in ASP. net mvc 3.0

This article mainly introduces the following content:

1. Introduction

Developers who have worked for DI for more than three years should be familiar with DI. If you are a beginner developer, I suggest you take a look at the materials and learn about DI and related concepts. Read the following:




In ASP. in versions earlier than net mvc 3, Abstract Factory and Service Locator are used as DI containers. In 3, you can use the new Dependency Resolver to combine the Container tool to implement DI more easily.

2. Dependency Resolution

What is Dependency Resolution?

A Controller requires a Repository, so this Repository is a dependency of the Controller.

The above is a traditional Deoendency example (in code ).

The Dependency Reolver is provided in ASP. net mvc 3, which provides us with a good Dependency Resolution.

When a component is required in the request, the Dependency Resolver will provide a corresponding control T.

3. Benefits

What are the advantages of Dependency Resolution?

A. Flexibility

Make the entire system architecture more flexible. Developers can focus more on architecture rather than function implementation.

B. Testability

This makes testing of the entire system easier. The test part and specific functional implementation dependencies are much smaller.

C. Extensibility

Enhanced scalability.

4. Use of IdependencyResolver

The DependencyResolver is a member of the System. web. mvc NameSpace and its job is quite simple: to provide a central registration point for your chosen IoC Container. prior to MVC 3, we often dealt with our chosen IoC container directly. in MVC 3, there is an independent action layer (the DependencyResolver Class) that we will interact with directly. whether your chosen IoC Container is Windsor, StructureMap or Unity, you can take advantage of this new feature.

The IdependencyResolver interface has two methods:

    object GetService(Type serviceType) IEnumerable<object> GetServices(Type serviceType)


How to use it is generally used in combination with an IoC Container.

Here are several examples:

Combined with Autofac:

I prefer Autofac, but I found that it is relatively complicated to use Autoc with IdependencyResolver. Research is required.

Combined with StructureMap:

   1. public class StructureMapDependencyResolver : IDependencyResolver   2.     {   3.        IContainer _container;   4.     5.     public StructureMapDependencyResolver(IContainer container)   6.         {   7.             _container = container;   8.         }   9.    10.    11.         public object GetService(Type serviceType)  12.         {  13.             object instance = _container.TryGetInstance(serviceType);  14.    15.             if (instance == null && !serviceType.IsAbstract)  16.             {  17.                 _container.Configure(c => c.AddType(serviceType, serviceType));  18.                 instance = _container.TryGetInstance(serviceType);  19.             }  20.    21.             return instance;  22.         }  23.    24.     public IEnumerable<object> GetServices(Type serviceType)  25.         {  26.             return _container.GetAllInstances(serviceType).Cast<object>();  27.         }  28.     }

Combined with Unity:

   1. public class UnityDependencyResolver : IDependencyResolver   2. {   3.     IUnityContainer _container;   4.     5.     public UnityDependencyResolver(IUnityContainer container)   6.     {   7.         _container = container;   8.     }   9.    10.     public object GetService(Type serviceType)  11.     {  12.         object instance;  13.         try  14.         {  15.             instance = _container.Resolve(serviceType);  16.             if (serviceType.IsAbstract || serviceType.IsInterface)  17.             {  18.                 return null;  19.             }  20.             return instance;  21.         }  22.         catch (Exception e)  23.         {  24.             return null;  25.         }  26.     }  27.    28.     public IEnumerable<object> GetServices(Type serviceType)  29.     {  30.         return _container.ResolveAll(serviceType);  31.     }  32. }

Combined with NInject:

public class NinjectDependencyResolver : IDependencyResolver    {        private readonly IKernel _kernel;        public NinjectDependencyResolver(IKernel kernel)        {            _kernel = kernel;        }        public object GetService(Type serviceType)        {            return _kernel.TryGet(serviceType, new IParameter[0]);        }        public IEnumerable<object> GetServices(Type serviceType)        {            return _kernel.GetAll(serviceType, new IParameter[0]);        }    }


The next step is to Register Service at Application Start and set Resolver.



#  IContainer container = new Container(#                 x =>#                 {#                     x.For<SomeService>().#                         Use<SomeService>().#                         WithCtorArg("stringResponse").#                         EqualTo("IoC Container: StructureMap.");#  #                     x.For<HomeController>().Use<HomeController>();#                 });#         DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));


##         var container = new UnityContainer();#  #         container#             .RegisterType<SomeService, SomeService>().#             Configure<InjectedMembers>().ConfigureInjectionFor#             <SomeService>(new InjectionConstructor("IoC Container: Unity."));#  #         container.RegisterType<HomeController, HomeController>();#  #         DependencyResolver.SetResolver(new UnityDependencyResolver(container));


   var kernel = new StandardKernel();            kernel.Bind<IMessenger>().To<SmsMessenger>();            kernel.Bind<IFilterProvider>().To<MessagingFilterProvider>();            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

5. Controller Injection:


6. View Injection:

You can read this article:


For more information about Activator and ViewEngine.














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: 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.