MVC3集成Unity 2.0

来源:互联网 发布:unity3d性能分析器 编辑:程序博客网 时间:2024/06/02 03:27

This blog posts shows a step-by-step instruction how tointegrate the Unity 2.0 dependency injection container in anASP.NET MVC 3 web application.

CreateMVC 3 project and add Unity 2.0

Create a new"ASP.NET MVC 3 Web Application" project in Visual Studio 2010. Forsimplicity, we will use the project template "Internet Application",which adds some some sample controllers and views to the project.
Download Unity 2.0 here from MSDN and run thesetup. By default, the setup will extract all Unity files toC:\Program Files(x86)\Microsoft Unity Application Block 2.0\. Copy all dll files from thesubfolderbin into your ASP.NET MVC 3 project. It is recommended to savethem in a new subfolder (for example "libs") in your project. Indetail, the project should now contain the following the dll files:

·       Microsoft.Practices.ServiceLocation.dll

·       Microsoft.Practices.Unity.Configuration.dll

·       Microsoft.Practices.Unity.dll

·       Microsoft.Practices.Unity.Interception.Configuration.dll

·       Microsoft.Practices.Unity.Interception.dll

In the SolutionExplorer, right click on "References" and click on "AddReference..." and select these five dll files in the tab"Browse" to reference the libraries in your project.

RegisterMVC 3 DependencyResolver

To use theUnity dependency injection container in the newly created ASP.NET MVC 3 projectwe first need an adapter class, that implements the interfaceIDependencyResolverand maps the method calls to a concrete Unity dependency injection container(an instance ofIUnityContainer, see this post):

publicclass UnityDependencyResolver :IDependencyResolver

{

 readonly IUnityContainer _container;

 public UnityDependencyResolver(IUnityContainer container)

 {

   this._container = container;

 }

 public objectGetService(Type serviceType)

 {

   try

   {

     return _container.Resolve(serviceType);

   }

   catch

   {

     return null;

   }

 }

 public IEnumerable<object>GetServices(TypeserviceType)

 {

   try

   {

     return _container.ResolveAll(serviceType);

   }

   catch

   {

     return new List<object>();

   }

 }

}

In the Global.asax.csfile we will set up a Unity dependency injection container in theApplication_Startmethod and use our little adapter class to register the Unity container as theservice locator for the ASP.NET MVC application.

protectedvoid Application_Start()

{

 [...]

 

 var container = new UnityContainer();

 container.RegisterType<IMessages, Messages>();

 DependencyResolver.SetResolver(new UnityDependencyResolver(container));

}

In the abovecode, we also register a type with the container using the RegisterTypemethod (you can find detailed information about configuring the Unity containerand in theMSDN library).
In this simplified example, we just register the type IMessages with theconcrete implementationMessages. The next section shows how this type isimplemented and used.

Resolvingdependencies

To test thedependency resolving, we modify the HomeController.cs and add a newpropertyMessages which is annotated with theDependency attributeand use this property in theIndex action:

publicclass HomeController : Controller {

 

 [Dependency]

 public IMessages Messages { get; set; }

 

 public ActionResult Index()

 {

   ViewBag.Message = Messages.Welcome;

   return View();

  }

 

 [...]

}

Of course,before we can build our ASP.NET application we need to implement theIMessagesinterface andMessages class:

publicinterface IMessages

{

 String Welcome { get; }

}

 

publicclass Messages : IMessages

{

 string IMessages.Welcome

 {

   get { return "Hello world fromUnity 2.0!"; }

 }

}

After buildingand starting the application the Unity dependency injection container shouldresolve the dependency that is defined in theHomeController and theapplication's start page should say "Hello world from Unity 2.0!".

You can download a sample Visual Studio 2010project containing all the source codehere

原创粉丝点击