Auto fac mvc以及進階應用(一)


Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Auto fac mvc以及進階應用(一)

  1. 1. Bryan Lin 2013/10/21
  2. 2.   AutoFac MVC的介紹 Registering Components ◦ Creating components ◦ Service types, names and keys ◦ Autowiring
  3. 3.  支援的專案類型: ◦ ASP.NET MVC4 ◦ ASP.NET MVC3 ◦ ASP.NET MVC2
  4. 4.  Project Setup ◦ Add references to the Autofac assemblies ◦ Register your controllers/dependencies ◦ Set the DependencyResolver
  5. 5.  Add References ◦ For NuGet, install the Autofac.Mvc4 package ◦ For manual references download Autofac and add references to:  Autofac.dll  Autofac.Integration.Mvc.dll
  6. 6.  Register Dependencies and Set the Dependency Resolver ◦ In Global.asax:
  7. 7.  ASP.NET MVC Registration and Usage ◦ ◦ ◦ ◦ ◦ ◦ Register Controllers Set the Dependency Resolver Register Model Binders Inject HTTP Abstractions Inject Dependencies into View Pages Inject Properties Into FilterAttributes
  8. 8.  Register Controllers ◦ Inside the Application_Start method in the Global.asax.cs register your controllers and their dependencies  You can do this manually  or you can use a provided extension method to register all the controllers in an assembly all at once
  9. 9.  Set the Dependency Resolver ◦ Use the static DependencyResolver.SetResolver method to let ASP.NET MVC know that it should locate services using the AutofacDependencyResolver
  10. 10.  Register Model Binders ◦ Similar to controllers, model binders (classes that implement IModelBinder) can be registered in Global.asax.cs ◦ Then using the Autofac.Integration.Mvc.ModelBinderTypeAttrib ute for your custom ModelBinder
  11. 11.  Inject HTTP Abstractions ◦ The MVC Integration includes an Autofac module that will add HTTP request lifetime scoped registrations for the HTTP abstraction classes.          HttpContextBase HttpRequestBase HttpResponseBase HttpServerUtilityBase HttpSessionStateBase HttpApplicationStateBase HttpBrowserCapabilitiesBase HttpCachePolicyBase VirtualPathProvider
  12. 12.  Inject HTTP Abstractions ◦ To use these abstractions add the AutofacWebTypesModule to the container using the standard RegisterModule method
  13. 13.  Inject Dependencies into View Pages ◦ You can make property injection available to your MVC views by adding the ViewRegistrationSource to your ContainerBuilder before building the application container
  14. 14.  Inject Dependencies into View Pages ◦ Your view page must inherit from one of the base classes that MVC supports for creating views ◦ When using the Razor view engine this will be the WebViewPage class
  15. 15.  Inject Dependencies into View Pages ◦ The ViewPage, ViewMasterPage and ViewUserContro l classes are supported when using the WebForms view engine
  16. 16.  Inject Dependencies into View Pages ◦ Ensure that your actual view page inherits from your custom base class ◦ This can be achieved using the @inherits directive inside your .cshtmlfile for the Razor view engine
  17. 17.  Inject Dependencies into View Pages ◦ When using the WebForms view engine you set the Inherits attribute on the @ Page directive inside you .aspx file instead
  18. 18.  Inject Properties Into FilterAttribute ◦ To make use of property injection for your filter attributes call the RegisterFilterProvider method on the ContainerBuilder before building your container and providing it to the AutofacDependencyResolver
  19. 19.  Inject Properties Into FilterAttribute ◦ Then you can add properties to your filter attributes and any matching dependencies that are registered in the container will be injected into the properties
  20. 20.  Inject Properties Into FilterAttribute ◦ The same simple approach applies to the other filter attribute types such as authorization attributes
  21. 21.  Inject Properties Into FilterAttribute ◦ After applying the attributes to your actions as required your work is done
  22. 22.  Creating components ◦ Components can be created using by:  Lambda expressions  Reflection  Providing a ready-made instance
  23. 23.  Creating components ◦ ContainerBuilder provides theRegister() family of methods to set this up ◦ Components are wired to services using the As() methods on ContainerBuilder:
  24. 24.  Creating components
  25. 25.  Creating components ◦ Reflection  Autofac is capable of inspecting a type, choosing an appropriate constructor, and creating an instance through reflection  The RegisterType<T>() and RegisterType(Type) metho ds set a component up this way:
  26. 26.  Creating components ◦ Expressions  Autofac can accept a delegate or lambda expression to be used as a component creator:
  27. 27.  Creating components ◦ Expressions  Complex Parameters - Constructor parameters can't always be declared with simple constant values. Rather than puzzling over how to construct a value of a certain type using an XML configuration syntax, use C#:
  28. 28.  Creating components ◦ Expressions  Property Injection - The preferred approach is to use property initialisers for this. The IComponentContext.ResolveOptional() method can be handy:
  29. 29.  Creating components ◦ Expressions  Property Injection - Alternatively, the PropertiesAutowired() configuration method will cause property injection:
  30. 30.  Creating components ◦ Expressions  Selection of an Implementer based on a Parameter Value - One of the great benefits of isolating component creation is that the concrete type can be varied. This is often done at runtime, not just configuration time:
  31. 31.  Creating components ◦ Expressions  Selection of an Implementer based on a Parameter Value - Using this registration would look like:
  32. 32.  Creating components ◦ Provided Instances  When integrating Autofac into an existing application there will sometimes be cases where a singleton instance already exists and needs to be used by components in the container.  Rather than tying those components directly to the singleton, it can be registered with the container as an instance:
  33. 33.  Creating components ◦ Open Generic Types  Autofac supports open generic types.  Use the RegisterGeneric() builder method:
  34. 34.  Creating components ◦ Open Generic Types  When a matching service type is requested from the container, Autofac will map this to an equivalent closed version of the implementation type:
  35. 35.  Creating components ◦ Default Registrations  If more than one component exposes the same service, Autofac will use the last registered component as the default provider of that service.  To override this behaviour, use the PreserveExistingDefaults() modifier:
  36. 36.  Service types, names and keys ◦ By Type  The default method of describing a service is as a type.  This example associates the IDeviceState typed service with the OnlineState component.  Instances of the component can be retrieved using the service type with the Resolve() method:
  37. 37.  Service types, names and keys ◦ By Name  Services can be further identified using a service name. Using this technique, the Named() registration method replaces As().  To retrieve a named service, the ResolveNamed() method is used:
  38. 38.  Service types, names and keys ◦ By Key  Using strings as component names is convenient in some cases, but in others we may wish to use keys of other types. Keyed services provide this ability.  For example, an enum may describe the different device states in our example:
  39. 39.  Service types, names and keys ◦ By Key  Each enum value corresponds to an implementation of the service:  The enum values can then be registered as keys for the implementations as shown below.
  40. 40.  Service types, names and keys ◦ By Key  Resolving Explicitly - The implementation can be resolved explicitly with ResolveKeyed():
  41. 41.  Service types, names and keys ◦ By Key  Resolving with an Index Autofac.Features.Indexed.IIndex<K,V> is a relationship type that Autofac implements automatically. Components that need to choose between service implementations based on a key can do so by taking a constructor parameter of type IIndex<K,V>.
  42. 42.  Autowiring ◦ Autowiring is the process of creating components by selecting a constructor according to the services available in the container. ◦ This is done via reflection, so that in effect the container adapts its component creation behaviour to the configured environment.
  43. 43.  Autowiring ◦ Choosing Constructors  Autofac automatically chooses the constructor with the most parameters that are able to be obtained from the container.  To select a different constructor, specify it when the component is registered:
  44. 44.  Autowiring ◦ Additional Constructor Arguments  There are two ways that additional constructor arguments can be provided - at registration time and at resolve time. Both will be used when autowiring instances.  At Registration - Use the WithParameters() method to associate parameters with a component that will be used every time the component is created:
  45. 45.  Autowiring ◦ Additional Constructor Arguments  At Resolve - You can pass Parameter instances to all of the Resolve() overloads.  Precedence - Parameters provided at Resolve() time will override any other parameter with the same name. Parameters provided at registration will override any possible service matches that exist in the container.
  46. 46.  Autowiring ◦ Making Autowiring Work for You  By far the greatest use for Autowiring is cutting down on repetitive configuration.  Wherever there are many similar components to register, Autowiring can be used with scanning:  This doesn't preclude you from subsequently overriding one of these registrations to meet special requirements or improve performance: