// This software is part of the Autofac IoC container // Copyright © 2011 Autofac Contributors // http://autofac.org // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Web; using System.Web.Mvc; using Autofac.Builder; using Autofac.Core; using Autofac.Features.Scanning; namespace Autofac.Integration.Mvc { /// /// Extends with methods to support ASP.NET MVC. /// public static class RegistrationExtensions { /// /// Share one instance of the component within the context of a single /// HTTP request. /// /// Registration limit type. /// Registration style. /// Activator data type. /// The registration to configure. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder InstancePerHttpRequest( this IRegistrationBuilder registration) { if (registration == null) throw new ArgumentNullException("registration"); return registration.InstancePerMatchingLifetimeScope(RequestLifetimeScopeProvider.HttpRequestTag); } /// /// Register types that implement IController in the provided assemblies. /// /// The container builder. /// Assemblies to scan for controllers. /// Registration builder allowing the controller components to be customised. public static IRegistrationBuilder RegisterControllers( this ContainerBuilder builder, params Assembly[] controllerAssemblies) { return builder.RegisterAssemblyTypes(controllerAssemblies) .Where(t => typeof(IController).IsAssignableFrom(t) && t.Name.EndsWith("Controller", StringComparison.Ordinal)); } /// /// Inject an IActionInvoker into the controller's ActionInvoker property. /// /// Limit type. /// Activator data. /// Registration style. /// The registration builder. /// A registration builder. public static IRegistrationBuilder InjectActionInvoker( this IRegistrationBuilder registrationBuilder) { return registrationBuilder.InjectActionInvoker(new TypedService(typeof(IActionInvoker))); } /// /// Inject an IActionInvoker into the controller's ActionInvoker property. /// /// Limit type. /// Activator data. /// Registration style. /// The registration builder. /// Service used to resolve the action invoker. /// A registration builder. public static IRegistrationBuilder InjectActionInvoker( this IRegistrationBuilder registrationBuilder, Service actionInvokerService) { if (registrationBuilder == null) throw new ArgumentNullException("registrationBuilder"); if (actionInvokerService == null) throw new ArgumentNullException("actionInvokerService"); return registrationBuilder.OnActivating(e => { var controller = e.Instance as Controller; if (controller != null) controller.ActionInvoker = (IActionInvoker)e.Context.ResolveService(actionInvokerService); }); } /// /// Registers the . /// /// The container builder. public static void RegisterModelBinderProvider(this ContainerBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); builder.RegisterType() .As() .SingleInstance(); } /// /// Sets a provided registration to act as an /// for the specified list of types. /// /// /// The registration for the type or object instance that will act as /// the model binder. /// /// /// The list of model for which the /// should be a model binder. /// /// /// Registration limit type. /// /// /// Activator data type. /// /// /// Registration style. /// /// /// An Autofac registration that can be modified as needed. /// /// /// Thrown if or is . /// /// /// Thrown if is empty or contains all /// values. /// /// /// /// The declarative mechanism of registering model binders with Autofac /// is through use of /// and the . /// This method is an imperative alternative. /// /// /// The two mechanisms are mutually exclusive. If you register a model /// binder using /// and register the same model binder with this method, the results /// are not automatically merged together - standard dependency /// registration/resolution rules will be used to manage the conflict. /// /// /// Any values provided in /// will be removed prior to registration. /// /// public static IRegistrationBuilder AsModelBinderForTypes(this IRegistrationBuilder registration, params Type[] types) where TActivatorData : IConcreteActivatorData where TRegistrationStyle : SingleRegistrationStyle { if (registration == null) { throw new ArgumentNullException("registration"); } if (types == null) { throw new ArgumentNullException("types"); } var typeList = types.Where(type => type != null).ToList(); if (typeList.Count == 0) { throw new ArgumentException(RegistrationExtensionsResources.InvalidModelBinderType, "types"); } return registration.As().WithMetadata(AutofacModelBinderProvider.MetadataKey, typeList); } /// /// Register types that implement in the provided assemblies /// and have a . /// /// The container builder. /// Assemblies to scan for model binders. /// A registration builder. /// /// Thrown if or is . /// /// /// /// The declarative mechanism of registering model binders with Autofac /// is through use of this method and the /// . /// If you would like more imperative control over registration for your /// model binders, see the /// method. /// /// /// The two mechanisms are mutually exclusive. If you register a model /// binder using /// and register the same model binder with this method, the results /// are not automatically merged together - standard dependency /// registration/resolution rules will be used to manage the conflict. /// /// /// This method only registers types that implement /// and are marked with the . /// The model binder must have the attribute because the /// uses /// the associated metadata - from the attribute(s) - to resolve the /// binder based on model type. If there aren't any attributes, there /// won't be any metadata, so the model binder will be technically /// registered but will never actually be resolved. /// /// /// If your model is not marked with the attribute, or if you don't want /// to use attributes, use the /// /// extension instead. /// /// public static IRegistrationBuilder RegisterModelBinders(this ContainerBuilder builder, params Assembly[] modelBinderAssemblies) { if (builder == null) throw new ArgumentNullException("builder"); if (modelBinderAssemblies == null) throw new ArgumentNullException("modelBinderAssemblies"); return builder.RegisterAssemblyTypes(modelBinderAssemblies) .Where(type => typeof(IModelBinder).IsAssignableFrom(type) && type.GetCustomAttributes(typeof(ModelBinderTypeAttribute), true).Length > 0) .As() .InstancePerHttpRequest() .WithMetadata(AutofacModelBinderProvider.MetadataKey, type => (from ModelBinderTypeAttribute attribute in type.GetCustomAttributes(typeof(ModelBinderTypeAttribute), true) from targetType in attribute.TargetTypes select targetType).ToList()); } /// /// Registers the . /// /// The container builder. public static void RegisterFilterProvider(this ContainerBuilder builder) { if (builder == null) throw new ArgumentNullException("builder"); foreach (var provider in FilterProviders.Providers.OfType().ToArray()) FilterProviders.Providers.Remove(provider); builder.RegisterType() .As() .SingleInstance(); } /// /// Cache instances in the web session. This implies external ownership (disposal is not /// available.) All dependencies must also have external ownership. /// /// /// It is strongly recommended that components cached per-session do not take dependencies on /// other services. /// /// Registration limit type. /// Registration style. /// Activator data type. /// The registration to configure. /// A registration builder allowing further configuration of the component. [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It is the responsibility of the registry to dispose of registrations.")] public static IRegistrationBuilder CacheInSession( this IRegistrationBuilder registration) where TActivatorData : IConcreteActivatorData where TSingleRegistrationStyle : SingleRegistrationStyle { if (registration == null) throw new ArgumentNullException("registration"); var services = registration.RegistrationData.Services.ToArray(); registration.RegistrationData.ClearServices(); return registration .ExternallyOwned() .OnRegistered(e => e.ComponentRegistry.Register(RegistrationBuilder .ForDelegate((c, p) => { var session = HttpContext.Current.Session; object result; lock (session.SyncRoot) { result = session[e.ComponentRegistration.Id.ToString()]; if (result == null) { result = c.ResolveComponent(e.ComponentRegistration, p); session[e.ComponentRegistration.Id.ToString()] = result; } } return result; }) .As(services) .InstancePerLifetimeScope() .ExternallyOwned() .CreateRegistration())); } /// /// Sets the provided registration to act as an for the specified controller action. /// /// The type of the controller. /// The registration. /// The action selector. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsActionFilterFor(this IRegistrationBuilder registration, Expression> actionSelector, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.ActionFilterMetadataKey, actionSelector, order); } /// /// Sets the provided registration to act as an for the specified controller. /// /// The type of the controller. /// The registration. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsActionFilterFor(this IRegistrationBuilder registration, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.ActionFilterMetadataKey, order); } /// /// Sets the provided registration to act as an for the specified controller action. /// /// The type of the controller. /// The registration. /// The action selector. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsAuthorizationFilterFor(this IRegistrationBuilder registration, Expression> actionSelector, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.AuthorizationFilterMetadataKey, actionSelector, order); } /// /// Sets the provided registration to act as an for the specified controller. /// /// The type of the controller. /// The registration. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsAuthorizationFilterFor(this IRegistrationBuilder registration, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.AuthorizationFilterMetadataKey, order); } /// /// Sets the provided registration to act as an for the specified controller action. /// /// The type of the controller. /// The registration. /// The action selector. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsExceptionFilterFor(this IRegistrationBuilder registration, Expression> actionSelector, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.ExceptionFilterMetadataKey, actionSelector, order); } /// /// Sets the provided registration to act as an for the specified controller. /// /// The type of the controller. /// The registration. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsExceptionFilterFor(this IRegistrationBuilder registration, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.ExceptionFilterMetadataKey, order); } /// /// Sets the provided registration to act as an for the specified controller action. /// /// The type of the controller. /// The registration. /// The action selector. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsResultFilterFor(this IRegistrationBuilder registration, Expression> actionSelector, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.ResultFilterMetadataKey, actionSelector, order); } /// /// Sets the provided registration to act as an for the specified controller. /// /// The type of the controller. /// The registration. /// The order in which the filter is applied. /// A registration builder allowing further configuration of the component. public static IRegistrationBuilder AsResultFilterFor(this IRegistrationBuilder registration, int order = Filter.DefaultOrder) where TController : IController { return AsFilterFor(registration, AutofacFilterProvider.ResultFilterMetadataKey, order); } static IRegistrationBuilder AsFilterFor(IRegistrationBuilder registration, string metadataKey, Expression> actionSelector, int order) where TController : IController { if (registration == null) throw new ArgumentNullException("registration"); if (actionSelector == null) throw new ArgumentNullException("actionSelector"); var limitType = registration.ActivatorData.Activator.LimitType; if (!limitType.IsAssignableTo()) { var message = string.Format(CultureInfo.CurrentCulture, RegistrationExtensionsResources.MustBeAssignableToFilterType, limitType.FullName, typeof(TFilter).FullName); throw new ArgumentException(message, "registration"); } var metadata = new FilterMetadata { ControllerType = typeof(TController), FilterScope = FilterScope.Action, MethodInfo = GetMethodInfo(actionSelector), Order = order }; return registration.As().WithMetadata(metadataKey, metadata); } static IRegistrationBuilder AsFilterFor(IRegistrationBuilder registration, string metadataKey, int order) where TController : IController { if (registration == null) throw new ArgumentNullException("registration"); var limitType = registration.ActivatorData.Activator.LimitType; if (!limitType.IsAssignableTo()) { var message = string.Format(CultureInfo.CurrentCulture, RegistrationExtensionsResources.MustBeAssignableToFilterType, limitType.FullName, typeof(TFilter).FullName); throw new ArgumentException(message, "registration"); } var metadata = new FilterMetadata { ControllerType = typeof(TController), FilterScope = FilterScope.Controller, MethodInfo = null, Order = order }; return registration.As().WithMetadata(metadataKey, metadata); } static MethodInfo GetMethodInfo(LambdaExpression expression) { var outermostExpression = expression.Body as MethodCallExpression; if (outermostExpression == null) throw new ArgumentException(RegistrationExtensionsResources.InvalidActionExpress); return outermostExpression.Method; } } }