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