Auto fac mvc以及進階應用(一)
Upcoming SlideShare
Loading in...5
×
 

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

on

  • 637 views

 

Statistics

Views

Total Views
637
Views on SlideShare
637
Embed Views
0

Actions

Likes
1
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

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

    • Bryan Lin 2013/10/21
    •   AutoFac MVC的介紹 Registering Components ◦ Creating components ◦ Service types, names and keys ◦ Autowiring
    •  支援的專案類型: ◦ ASP.NET MVC4 ◦ ASP.NET MVC3 ◦ ASP.NET MVC2
    •  Project Setup ◦ Add references to the Autofac assemblies ◦ Register your controllers/dependencies ◦ Set the DependencyResolver
    •  Add References ◦ For NuGet, install the Autofac.Mvc4 package ◦ For manual references download Autofac and add references to:  Autofac.dll  Autofac.Integration.Mvc.dll
    •  Register Dependencies and Set the Dependency Resolver ◦ In Global.asax:
    •  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
    •  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
    •  Set the Dependency Resolver ◦ Use the static DependencyResolver.SetResolver method to let ASP.NET MVC know that it should locate services using the AutofacDependencyResolver
    •  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
    •  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
    •  Inject HTTP Abstractions ◦ To use these abstractions add the AutofacWebTypesModule to the container using the standard RegisterModule method
    •  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
    •  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
    •  Inject Dependencies into View Pages ◦ The ViewPage, ViewMasterPage and ViewUserContro l classes are supported when using the WebForms view engine
    •  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
    •  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
    •  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
    •  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
    •  Inject Properties Into FilterAttribute ◦ The same simple approach applies to the other filter attribute types such as authorization attributes
    •  Inject Properties Into FilterAttribute ◦ After applying the attributes to your actions as required your work is done
    •  Creating components ◦ Components can be created using by:  Lambda expressions  Reflection  Providing a ready-made instance
    •  Creating components ◦ ContainerBuilder provides theRegister() family of methods to set this up ◦ Components are wired to services using the As() methods on ContainerBuilder:
    •  Creating components
    •  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:
    •  Creating components ◦ Expressions  Autofac can accept a delegate or lambda expression to be used as a component creator:
    •  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#:
    •  Creating components ◦ Expressions  Property Injection - The preferred approach is to use property initialisers for this. The IComponentContext.ResolveOptional() method can be handy:
    •  Creating components ◦ Expressions  Property Injection - Alternatively, the PropertiesAutowired() configuration method will cause property injection:
    •  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:
    •  Creating components ◦ Expressions  Selection of an Implementer based on a Parameter Value - Using this registration would look like:
    •  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:
    •  Creating components ◦ Open Generic Types  Autofac supports open generic types.  Use the RegisterGeneric() builder method:
    •  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:
    •  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:
    •  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:
    •  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:
    •  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:
    •  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.
    •  Service types, names and keys ◦ By Key  Resolving Explicitly - The implementation can be resolved explicitly with ResolveKeyed():
    •  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>.
    •  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.
    •  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:
    •  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:
    •  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.
    •  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: