mirror of
https://github.com/lidarr/lidarr.git
synced 2025-08-14 10:47:08 -07:00
upgraded to autofac 3. created nancy only mode for nzbdrone.exe /n
This commit is contained in:
parent
177f88303c
commit
b0940ed8de
77 changed files with 3930 additions and 113 deletions
133
Autofac.Integration.Mvc/Autofac.Integration.Mvc.csproj
Normal file
133
Autofac.Integration.Mvc/Autofac.Integration.Mvc.csproj
Normal file
|
@ -0,0 +1,133 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>8.0.30703</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{DD874E64-C7EC-464D-925F-CF4A709EDEEF}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>Autofac.Integration.Mvc</RootNamespace>
|
||||
<AssemblyName>Autofac.Integration.Mvc</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\..\</SolutionDir>
|
||||
<RestorePackages>true</RestorePackages>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<CodeAnalysisRuleSet>..\..\..\Build\Full.ruleset</CodeAnalysisRuleSet>
|
||||
<RunCodeAnalysis>false</RunCodeAnalysis>
|
||||
<DocumentationFile>bin\Debug\Autofac.Integration.Mvc.xml</DocumentationFile>
|
||||
<CodeAnalysisIgnoreGeneratedCode>false</CodeAnalysisIgnoreGeneratedCode>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<CodeAnalysisRuleSet>..\..\..\Build\Full.ruleset</CodeAnalysisRuleSet>
|
||||
<RunCodeAnalysis>true</RunCodeAnalysis>
|
||||
<DocumentationFile>bin\Release\Autofac.Integration.Mvc.xml</DocumentationFile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<SignAssembly>false</SignAssembly>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<AssemblyOriginatorKeyFile>..\..\..\Build\SharedKey.snk</AssemblyOriginatorKeyFile>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Autofac">
|
||||
<HintPath>..\packages\Autofac.3.0.1\lib\net40\Autofac.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libraries\MVC3\Microsoft.Web.Infrastructure.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Web" />
|
||||
<Reference Include="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libraries\MVC3\System.Web.Helpers.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libraries\MVC3\System.Web.Mvc.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libraries\MVC3\System.Web.Razor.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libraries\MVC3\System.Web.WebPages.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libraries\MVC3\System.Web.WebPages.Deployment.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\Libraries\MVC3\System.Web.WebPages.Razor.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="AutofacDependencyResolver.cs" />
|
||||
<Compile Include="AutofacFilterProvider.cs" />
|
||||
<Compile Include="AutofacModelBinderProvider.cs" />
|
||||
<Compile Include="AutofacWebTypesModule.cs" />
|
||||
<Compile Include="FilterMetadata.cs" />
|
||||
<Compile Include="RegistrationExtensionsResources.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
<DependentUpon>RegistrationExtensionsResources.resx</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="RequestLifetimeScopeProvider.cs" />
|
||||
<Compile Include="ExtensibleActionInvoker.cs" />
|
||||
<Compile Include="ILifetimeScopeProvider.cs" />
|
||||
<Compile Include="ModelBinderTypeAttribute.cs" />
|
||||
<Compile Include="PreApplicationStartCode.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="RegistrationExtensions.cs" />
|
||||
<Compile Include="RequestLifetimeHttpModule.cs" />
|
||||
<Compile Include="RequestLifetimeScopeProviderResources.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
<DependentUpon>RequestLifetimeScopeProviderResources.resx</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="ViewRegistrationSource.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="RegistrationExtensionsResources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>RegistrationExtensionsResources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
<EmbeddedResource Include="RequestLifetimeScopeProviderResources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>RequestLifetimeScopeProviderResources.Designer.cs</LastGenOutput>
|
||||
<SubType>Designer</SubType>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<Import Project="$(SolutionDir)\.nuget\nuget.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
164
Autofac.Integration.Mvc/AutofacDependencyResolver.cs
Normal file
164
Autofac.Integration.Mvc/AutofacDependencyResolver.cs
Normal file
|
@ -0,0 +1,164 @@
|
|||
// 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.Collections.Generic;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Autofac implementation of the <see cref="IDependencyResolver"/> interface.
|
||||
/// </summary>
|
||||
public class AutofacDependencyResolver : IDependencyResolver
|
||||
{
|
||||
readonly ILifetimeScope _container;
|
||||
readonly Action<ContainerBuilder> _configurationAction;
|
||||
ILifetimeScopeProvider _lifetimeScopeProvider;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AutofacDependencyResolver"/> class.
|
||||
/// </summary>
|
||||
/// <param name="container">The container that nested lifetime scopes will be create from.</param>
|
||||
public AutofacDependencyResolver(ILifetimeScope container)
|
||||
{
|
||||
if (container == null) throw new ArgumentNullException("container");
|
||||
_container = container;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AutofacDependencyResolver"/> class.
|
||||
/// </summary>
|
||||
/// <param name="container">The container that nested lifetime scopes will be create from.</param>
|
||||
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/>
|
||||
/// that adds component registations visible only in nested lifetime scopes.</param>
|
||||
public AutofacDependencyResolver(ILifetimeScope container, Action<ContainerBuilder> configurationAction)
|
||||
: this(container)
|
||||
{
|
||||
if (configurationAction == null) throw new ArgumentNullException("configurationAction");
|
||||
_configurationAction = configurationAction;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AutofacDependencyResolver"/> class.
|
||||
/// </summary>
|
||||
/// <param name="container">The container that nested lifetime scopes will be create from.</param>
|
||||
/// <param name="lifetimeScopeProvider">A <see cref="ILifetimeScopeProvider"/> implementation for
|
||||
/// creating new lifetime scopes.</param>
|
||||
public AutofacDependencyResolver(ILifetimeScope container, ILifetimeScopeProvider lifetimeScopeProvider) :
|
||||
this(container)
|
||||
{
|
||||
if (lifetimeScopeProvider == null) throw new ArgumentNullException("lifetimeScopeProvider");
|
||||
_lifetimeScopeProvider = lifetimeScopeProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AutofacDependencyResolver"/> class.
|
||||
/// </summary>
|
||||
/// <param name="container">The container that nested lifetime scopes will be create from.</param>
|
||||
/// <param name="lifetimeScopeProvider">A <see cref="ILifetimeScopeProvider"/> implementation for
|
||||
/// creating new lifetime scopes.</param>
|
||||
/// <param name="configurationAction">Action on a <see cref="ContainerBuilder"/>
|
||||
/// that adds component registations visible only in nested lifetime scopes.</param>
|
||||
public AutofacDependencyResolver(ILifetimeScope container, ILifetimeScopeProvider lifetimeScopeProvider, Action<ContainerBuilder> configurationAction)
|
||||
: this(container, lifetimeScopeProvider)
|
||||
{
|
||||
if (configurationAction == null) throw new ArgumentNullException("configurationAction");
|
||||
_configurationAction = configurationAction;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Autofac implementation of the dependency resolver.
|
||||
/// </summary>
|
||||
public static AutofacDependencyResolver Current
|
||||
{
|
||||
get
|
||||
{
|
||||
// Issue 351: We can't necessarily cast the current dependency resolver
|
||||
// to AutofacDependencyResolver because diagnostic systems like Glimpse
|
||||
// will wrap/proxy the resolver. Instead we need to register the resolver
|
||||
// on the fly with the request lifetime scope and resolve it accordingly.
|
||||
return DependencyResolver.Current.GetService<AutofacDependencyResolver>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The lifetime containing components for processing the current HTTP request.
|
||||
/// </summary>
|
||||
public ILifetimeScope RequestLifetimeScope
|
||||
{
|
||||
get
|
||||
{
|
||||
// Issue 351: Register the AutofacDependencyResolver with
|
||||
// the request lifetime scope so the current resolver can
|
||||
// be retrieved without having to cast it directly to
|
||||
// this specific type.
|
||||
Action<ContainerBuilder> composite = builder =>
|
||||
{
|
||||
if (this._configurationAction != null)
|
||||
{
|
||||
this._configurationAction(builder);
|
||||
}
|
||||
builder.RegisterInstance(this).As<AutofacDependencyResolver>();
|
||||
};
|
||||
if (_lifetimeScopeProvider == null)
|
||||
{
|
||||
_lifetimeScopeProvider = new RequestLifetimeScopeProvider(_container);
|
||||
}
|
||||
return _lifetimeScopeProvider.GetLifetimeScope(composite);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the application container that was provided to the constructor.
|
||||
/// </summary>
|
||||
public ILifetimeScope ApplicationContainer
|
||||
{
|
||||
get { return _container; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get a single instance of a service.
|
||||
/// </summary>
|
||||
/// <param name="serviceType">Type of the service.</param>
|
||||
/// <returns>The single instance if resolved; otherwise, <c>null</c>.</returns>
|
||||
public object GetService(Type serviceType)
|
||||
{
|
||||
return RequestLifetimeScope.ResolveOptional(serviceType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all available instances of a services.
|
||||
/// </summary>
|
||||
/// <param name="serviceType">Type of the service.</param>
|
||||
/// <returns>The list of instances if any were resolved; otherwise, an empty list.</returns>
|
||||
public IEnumerable<object> GetServices(Type serviceType)
|
||||
{
|
||||
var enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType);
|
||||
var instance = RequestLifetimeScope.Resolve(enumerableServiceType);
|
||||
return (IEnumerable<object>)instance;
|
||||
}
|
||||
}
|
||||
}
|
171
Autofac.Integration.Mvc/AutofacFilterProvider.cs
Normal file
171
Autofac.Integration.Mvc/AutofacFilterProvider.cs
Normal file
|
@ -0,0 +1,171 @@
|
|||
// This software is part of the Autofac IoC container
|
||||
// Copyright © 2012 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.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Web.Mvc;
|
||||
using System.Web.Mvc.Async;
|
||||
using Autofac.Features.Metadata;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Defines a filter provider for filter attributes that performs property injection.
|
||||
/// </summary>
|
||||
public class AutofacFilterProvider : FilterAttributeFilterProvider
|
||||
{
|
||||
class FilterContext
|
||||
{
|
||||
public ActionDescriptor ActionDescriptor { get; set; }
|
||||
public ILifetimeScope LifetimeScope { get; set; }
|
||||
public Type ControllerType { get; set; }
|
||||
public List<Filter> Filters { get; set; }
|
||||
}
|
||||
|
||||
internal static string ActionFilterMetadataKey = "AutofacMvcActionFilter";
|
||||
|
||||
internal static string AuthorizationFilterMetadataKey = "AutofacMvcAuthorizationFilter";
|
||||
|
||||
internal static string ExceptionFilterMetadataKey = "AutofacMvcExceptionFilter";
|
||||
|
||||
internal static string ResultFilterMetadataKey = "AutofacMvcResultFilter";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="AutofacFilterProvider"/> class.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The <c>false</c> constructor parameter passed to base here ensures that attribute instances are not cached.
|
||||
/// </remarks>
|
||||
public AutofacFilterProvider() : base(false)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Aggregates the filters from all of the filter providers into one collection.
|
||||
/// </summary>
|
||||
/// <param name="controllerContext">The controller context.</param>
|
||||
/// <param name="actionDescriptor">The action descriptor.</param>
|
||||
/// <returns>
|
||||
/// The collection filters from all of the filter providers with properties injected.
|
||||
/// </returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// Thrown if <paramref name="controllerContext" /> is <see langword="null" />.
|
||||
/// </exception>
|
||||
public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
|
||||
{
|
||||
if (controllerContext == null)
|
||||
{
|
||||
throw new ArgumentNullException("controllerContext");
|
||||
}
|
||||
var filters = base.GetFilters(controllerContext, actionDescriptor).ToList();
|
||||
var lifetimeScope = AutofacDependencyResolver.Current.RequestLifetimeScope;
|
||||
|
||||
if (lifetimeScope != null)
|
||||
{
|
||||
foreach (var filter in filters)
|
||||
lifetimeScope.InjectProperties(filter.Instance);
|
||||
|
||||
var controllerType = controllerContext.Controller.GetType();
|
||||
|
||||
var filterContext = new FilterContext
|
||||
{
|
||||
ActionDescriptor = actionDescriptor,
|
||||
LifetimeScope = lifetimeScope,
|
||||
ControllerType = controllerType,
|
||||
Filters = filters
|
||||
};
|
||||
|
||||
ResolveControllerScopedFilters(filterContext);
|
||||
|
||||
ResolveActionScopedFilters<ReflectedActionDescriptor>(filterContext, d => d.MethodInfo);
|
||||
ResolveActionScopedFilters<ReflectedAsyncActionDescriptor>(filterContext, d => d.AsyncMethodInfo);
|
||||
}
|
||||
|
||||
return filters.ToArray();
|
||||
}
|
||||
|
||||
static void ResolveControllerScopedFilters(FilterContext filterContext)
|
||||
{
|
||||
ResolveControllerScopedFilter<IActionFilter>(filterContext, ActionFilterMetadataKey);
|
||||
ResolveControllerScopedFilter<IAuthorizationFilter>(filterContext, AuthorizationFilterMetadataKey);
|
||||
ResolveControllerScopedFilter<IExceptionFilter>(filterContext, ExceptionFilterMetadataKey);
|
||||
ResolveControllerScopedFilter<IResultFilter>(filterContext, ResultFilterMetadataKey);
|
||||
}
|
||||
|
||||
static void ResolveControllerScopedFilter<TFilter>(FilterContext filterContext, string metadataKey)
|
||||
where TFilter : class
|
||||
{
|
||||
var actionFilters = filterContext.LifetimeScope.Resolve<IEnumerable<Meta<Lazy<TFilter>>>>();
|
||||
|
||||
foreach (var actionFilter in actionFilters.Where(a => a.Metadata.ContainsKey(metadataKey) && a.Metadata[metadataKey] is FilterMetadata))
|
||||
{
|
||||
var metadata = (FilterMetadata)actionFilter.Metadata[metadataKey];
|
||||
if (metadata.ControllerType != null
|
||||
&& metadata.ControllerType.IsAssignableFrom(filterContext.ControllerType)
|
||||
&& metadata.FilterScope == FilterScope.Controller
|
||||
&& metadata.MethodInfo == null)
|
||||
{
|
||||
var filter = new Filter(actionFilter.Value.Value, FilterScope.Controller, metadata.Order);
|
||||
filterContext.Filters.Add(filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ResolveActionScopedFilters<T>(FilterContext filterContext, Func<T, MethodInfo> methodSelector)
|
||||
where T : ActionDescriptor
|
||||
{
|
||||
var actionDescriptor = filterContext.ActionDescriptor as T;
|
||||
if (actionDescriptor == null) return;
|
||||
|
||||
var methodInfo = methodSelector(actionDescriptor);
|
||||
|
||||
ResolveActionScopedFilter<IActionFilter>(filterContext, methodInfo, ActionFilterMetadataKey);
|
||||
ResolveActionScopedFilter<IAuthorizationFilter>(filterContext, methodInfo, AuthorizationFilterMetadataKey);
|
||||
ResolveActionScopedFilter<IExceptionFilter>(filterContext, methodInfo, ExceptionFilterMetadataKey);
|
||||
ResolveActionScopedFilter<IResultFilter>(filterContext, methodInfo, ResultFilterMetadataKey);
|
||||
}
|
||||
|
||||
static void ResolveActionScopedFilter<TFilter>(FilterContext filterContext, MethodInfo methodInfo, string metadataKey)
|
||||
where TFilter : class
|
||||
{
|
||||
var actionFilters = filterContext.LifetimeScope.Resolve<IEnumerable<Meta<Lazy<TFilter>>>>();
|
||||
|
||||
foreach (var actionFilter in actionFilters.Where(a => a.Metadata.ContainsKey(metadataKey) && a.Metadata[metadataKey] is FilterMetadata))
|
||||
{
|
||||
var metadata = (FilterMetadata)actionFilter.Metadata[metadataKey];
|
||||
if (metadata.ControllerType != null
|
||||
&& metadata.ControllerType.IsAssignableFrom(filterContext.ControllerType)
|
||||
&& metadata.FilterScope == FilterScope.Action
|
||||
&& metadata.MethodInfo.GetBaseDefinition() == methodInfo.GetBaseDefinition())
|
||||
{
|
||||
var filter = new Filter(actionFilter.Value.Value, FilterScope.Action, metadata.Order);
|
||||
filterContext.Filters.Add(filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
59
Autofac.Integration.Mvc/AutofacModelBinderProvider.cs
Normal file
59
Autofac.Integration.Mvc/AutofacModelBinderProvider.cs
Normal file
|
@ -0,0 +1,59 @@
|
|||
// 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.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web.Mvc;
|
||||
using Autofac.Features.Metadata;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Autofac implementation of the <see cref="IModelBinderProvider"/> interface.
|
||||
/// </summary>
|
||||
public class AutofacModelBinderProvider : IModelBinderProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Metadata key for the supported model types.
|
||||
/// </summary>
|
||||
internal static readonly string MetadataKey = "SupportedModelTypes";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the model binder associated with the provided model type.
|
||||
/// </summary>
|
||||
/// <param name="modelType">Type of the model.</param>
|
||||
/// <returns>An <see cref="IModelBinder"/> instance if found; otherwise, <c>null</c>.</returns>
|
||||
public IModelBinder GetBinder(Type modelType)
|
||||
{
|
||||
var modelBinders = DependencyResolver.Current.GetServices<Meta<Lazy<IModelBinder>>>();
|
||||
|
||||
var modelBinder = modelBinders
|
||||
.Where(binder => binder.Metadata.ContainsKey(MetadataKey))
|
||||
.FirstOrDefault(binder => ((List<Type>)binder.Metadata[MetadataKey]).Contains(modelType));
|
||||
return (modelBinder != null) ? modelBinder.Value.Value : null;
|
||||
}
|
||||
}
|
||||
}
|
178
Autofac.Integration.Mvc/AutofacWebTypesModule.cs
Normal file
178
Autofac.Integration.Mvc/AutofacWebTypesModule.cs
Normal file
|
@ -0,0 +1,178 @@
|
|||
// 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.Web;
|
||||
using System.Web.Hosting;
|
||||
using System.Web.Mvc;
|
||||
using System.Web.Routing;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Dependency injection module that registers abstractions for common
|
||||
/// web application properties.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This <see cref="Autofac.Module"/> is primarily used during
|
||||
/// application startup (in <c>Global.asax</c>) to register
|
||||
/// mappings from commonly referenced contextual application properties
|
||||
/// to their corresponding abstraction.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The following mappings are made:
|
||||
/// </para>
|
||||
/// <list type="table">
|
||||
/// <listheader>
|
||||
/// <term>Common Construct</term>
|
||||
/// <description>Abstraction</description>
|
||||
/// </listheader>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current</c></term>
|
||||
/// <description><see cref="System.Web.HttpContextBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Application</c></term>
|
||||
/// <description><see cref="System.Web.HttpApplicationStateBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Request</c></term>
|
||||
/// <description><see cref="System.Web.HttpRequestBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Request.Browser</c></term>
|
||||
/// <description><see cref="System.Web.HttpBrowserCapabilitiesBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Request.Files</c></term>
|
||||
/// <description><see cref="System.Web.HttpFileCollectionBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Request.RequestContext</c></term>
|
||||
/// <description><see cref="System.Web.Routing.RequestContext"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Response</c></term>
|
||||
/// <description><see cref="System.Web.HttpResponseBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Response.Cache</c></term>
|
||||
/// <description><see cref="System.Web.HttpCachePolicyBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Server</c></term>
|
||||
/// <description><see cref="System.Web.HttpServerUtilityBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HttpContext.Current.Session</c></term>
|
||||
/// <description><see cref="System.Web.HttpSessionStateBase"/></description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <term><c>HostingEnvironment.VirtualPathProvider</c></term>
|
||||
/// <description><see cref="System.Web.Hosting.VirtualPathProvider"/></description>
|
||||
/// </item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// In addition, the <see cref="System.Web.Mvc.UrlHelper"/> type is registered
|
||||
/// for construction based on the current <see cref="System.Web.Routing.RequestContext"/>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The lifetime for each of these items is one web request.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public class AutofacWebTypesModule : Module
|
||||
{
|
||||
/// <summary>
|
||||
/// Registers web abstractions with dependency injection.
|
||||
/// </summary>
|
||||
/// <param name="builder">
|
||||
/// The <see cref="Autofac.ContainerBuilder"/> in which registration
|
||||
/// should take place.
|
||||
/// </param>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// This method registers mappings between common current context-related
|
||||
/// web constructs and their associated abstract counterparts. See
|
||||
/// <see cref="Autofac.Integration.Mvc.AutofacWebTypesModule"/> for the complete
|
||||
/// list of mappings that get registered.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
protected override void Load(ContainerBuilder builder)
|
||||
{
|
||||
builder.Register(c => new HttpContextWrapper(HttpContext.Current))
|
||||
.As<HttpContextBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
// HttpContext properties
|
||||
builder.Register(c => c.Resolve<HttpContextBase>().Request)
|
||||
.As<HttpRequestBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
builder.Register(c => c.Resolve<HttpContextBase>().Response)
|
||||
.As<HttpResponseBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
builder.Register(c => c.Resolve<HttpContextBase>().Server)
|
||||
.As<HttpServerUtilityBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
builder.Register(c => c.Resolve<HttpContextBase>().Session)
|
||||
.As<HttpSessionStateBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
builder.Register(c => c.Resolve<HttpContextBase>().Application)
|
||||
.As<HttpApplicationStateBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
// HttpRequest properties
|
||||
builder.Register(c => c.Resolve<HttpRequestBase>().Browser)
|
||||
.As<HttpBrowserCapabilitiesBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
builder.Register(c => c.Resolve<HttpRequestBase>().Files)
|
||||
.As<HttpFileCollectionBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
builder.Register(c => c.Resolve<HttpRequestBase>().RequestContext)
|
||||
.As<RequestContext>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
// HttpResponse properties
|
||||
builder.Register(c => c.Resolve<HttpResponseBase>().Cache)
|
||||
.As<HttpCachePolicyBase>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
// HostingEnvironment properties
|
||||
builder.Register(c => HostingEnvironment.VirtualPathProvider)
|
||||
.As<VirtualPathProvider>()
|
||||
.InstancePerHttpRequest();
|
||||
|
||||
// MVC types
|
||||
builder.Register(c => new UrlHelper(c.Resolve<RequestContext>()))
|
||||
.As<UrlHelper>()
|
||||
.InstancePerHttpRequest();
|
||||
}
|
||||
}
|
||||
}
|
87
Autofac.Integration.Mvc/ExtensibleActionInvoker.cs
Normal file
87
Autofac.Integration.Mvc/ExtensibleActionInvoker.cs
Normal file
|
@ -0,0 +1,87 @@
|
|||
// 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.Web.Mvc;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Injects services from the container into the ASP.NET MVC invocation pipeline.
|
||||
/// This is a Async Controller Action Invoker which can be used for both async and non-async scenarios
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Action methods can include parameters that will be resolved from the
|
||||
/// container, along with regular parameters.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public class ExtensibleActionInvoker : System.Web.Mvc.Async.AsyncControllerActionInvoker
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the parameter value.
|
||||
/// </summary>
|
||||
/// <param name="controllerContext">The controller context.</param><param name="parameterDescriptor">The parameter descriptor.</param>
|
||||
/// <returns>
|
||||
/// The parameter value.
|
||||
/// </returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// Thrown if <paramref name="parameterDescriptor" /> is <see langword="null" />.
|
||||
/// </exception>
|
||||
protected override object GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
|
||||
{
|
||||
if (parameterDescriptor == null)
|
||||
{
|
||||
throw new ArgumentNullException("parameterDescriptor");
|
||||
}
|
||||
|
||||
// Only resolve parameter values if injection is enabled.
|
||||
var context = AutofacDependencyResolver.Current.RequestLifetimeScope;
|
||||
var value = context.ResolveOptional(parameterDescriptor.ParameterType);
|
||||
|
||||
if (value == null)
|
||||
{
|
||||
// Issue #368
|
||||
// If injection is enabled and the value can't be resolved, fall back to
|
||||
// the default behavior. Or if injection isn't enabled, fall back.
|
||||
// Unfortunately we can't do much to pre-determine if model binding will succeed
|
||||
// because model binding "knows" about a lot of stuff like arrays, certain generic
|
||||
// collection types, type converters, and other stuff that may or may not fail.
|
||||
try
|
||||
{
|
||||
value = base.GetParameterValue(controllerContext, parameterDescriptor);
|
||||
}
|
||||
catch (MissingMethodException)
|
||||
{
|
||||
// Don't do anything - this means the default model binder couldn't
|
||||
// activate a new instance or figure out some other way to model
|
||||
// bind it.
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
62
Autofac.Integration.Mvc/FilterMetadata.cs
Normal file
62
Autofac.Integration.Mvc/FilterMetadata.cs
Normal file
|
@ -0,0 +1,62 @@
|
|||
// This software is part of the Autofac IoC container
|
||||
// Copyright © 2012 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.ComponentModel;
|
||||
using System.Reflection;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Metadata interface for filter registrations.
|
||||
/// </summary>
|
||||
internal class FilterMetadata
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the type of the controller.
|
||||
/// </summary>
|
||||
[DefaultValue(null)]
|
||||
public Type ControllerType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the filter scope.
|
||||
/// </summary>
|
||||
[DefaultValue(FilterScope.First)]
|
||||
public FilterScope FilterScope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the method info.
|
||||
/// </summary>
|
||||
[DefaultValue(null)]
|
||||
public MethodInfo MethodInfo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the order in which the filter is applied.
|
||||
/// </summary>
|
||||
[DefaultValue(-1)]
|
||||
public int Order { get; set; }
|
||||
}
|
||||
}
|
56
Autofac.Integration.Mvc/ILifetimeScopeProvider.cs
Normal file
56
Autofac.Integration.Mvc/ILifetimeScopeProvider.cs
Normal file
|
@ -0,0 +1,56 @@
|
|||
// 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;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Implementors are able to control the creation of nested lifetime scopes.
|
||||
/// </summary>
|
||||
public interface ILifetimeScopeProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a nested lifetime scope that services can be resolved from.
|
||||
/// </summary>
|
||||
/// <param name="configurationAction">
|
||||
/// A configuration action that will execute during lifetime scope creation.
|
||||
/// </param>
|
||||
/// <returns>A new or existing nested lifetime scope.</returns>
|
||||
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
|
||||
ILifetimeScope GetLifetimeScope(Action<ContainerBuilder> configurationAction);
|
||||
|
||||
/// <summary>
|
||||
/// Ends the current lifetime scope.
|
||||
/// </summary>
|
||||
void EndLifetimeScope();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the global, application-wide container.
|
||||
/// </summary>
|
||||
ILifetimeScope ApplicationContainer { get; }
|
||||
}
|
||||
}
|
64
Autofac.Integration.Mvc/ModelBinderTypeAttribute.cs
Normal file
64
Autofac.Integration.Mvc/ModelBinderTypeAttribute.cs
Normal file
|
@ -0,0 +1,64 @@
|
|||
// 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.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Indicates what types a model binder supports.
|
||||
/// </summary>
|
||||
[SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
|
||||
public sealed class ModelBinderTypeAttribute : Attribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the target types.
|
||||
/// </summary>
|
||||
public IEnumerable<Type> TargetTypes { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ModelBinderTypeAttribute"/> class.
|
||||
/// </summary>
|
||||
/// <param name="targetTypes">The target types.</param>
|
||||
public ModelBinderTypeAttribute(params Type[] targetTypes)
|
||||
{
|
||||
if (targetTypes == null) throw new ArgumentNullException("targetTypes");
|
||||
TargetTypes = targetTypes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ModelBinderTypeAttribute"/> class.
|
||||
/// </summary>
|
||||
/// <param name="targetType">The target type.</param>
|
||||
public ModelBinderTypeAttribute(Type targetType)
|
||||
{
|
||||
if (targetType == null) throw new ArgumentNullException("targetType");
|
||||
TargetTypes = new Type[] { targetType };
|
||||
}
|
||||
}
|
||||
}
|
51
Autofac.Integration.Mvc/PreApplicationStartCode.cs
Normal file
51
Autofac.Integration.Mvc/PreApplicationStartCode.cs
Normal file
|
@ -0,0 +1,51 @@
|
|||
// 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.ComponentModel;
|
||||
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Container class for the ASP.NET application startup method.
|
||||
/// </summary>
|
||||
[EditorBrowsable(EditorBrowsableState.Never)]
|
||||
public static class PreApplicationStartCode
|
||||
{
|
||||
private static bool _startWasCalled;
|
||||
|
||||
/// <summary>
|
||||
/// Performs ASP.NET application startup logic early in the pipeline.
|
||||
/// </summary>
|
||||
public static void Start()
|
||||
{
|
||||
// Guard against multiple calls. All Start calls are made on the same thread, so no lock needed here.
|
||||
if (_startWasCalled) return;
|
||||
|
||||
_startWasCalled = true;
|
||||
DynamicModuleUtility.RegisterModule(typeof(RequestLifetimeHttpModule));
|
||||
}
|
||||
}
|
||||
}
|
12
Autofac.Integration.Mvc/Properties/AssemblyInfo.cs
Normal file
12
Autofac.Integration.Mvc/Properties/AssemblyInfo.cs
Normal file
|
@ -0,0 +1,12 @@
|
|||
using System;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Web;
|
||||
using Autofac.Integration.Mvc;
|
||||
|
||||
[assembly: AssemblyTitle("Autofac.Integration.Mvc")]
|
||||
[assembly: AssemblyDescription("Autofac ASP.NET MVC 4 Integration")]
|
||||
[assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mvc, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")]
|
||||
[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")]
|
||||
[assembly: ComVisible(false)]
|
510
Autofac.Integration.Mvc/RegistrationExtensions.cs
Normal file
510
Autofac.Integration.Mvc/RegistrationExtensions.cs
Normal file
|
@ -0,0 +1,510 @@
|
|||
// 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
|
||||
{
|
||||
/// <summary>
|
||||
/// Extends <see cref="ContainerBuilder"/> with methods to support ASP.NET MVC.
|
||||
/// </summary>
|
||||
public static class RegistrationExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Share one instance of the component within the context of a single
|
||||
/// HTTP request.
|
||||
/// </summary>
|
||||
/// <typeparam name="TLimit">Registration limit type.</typeparam>
|
||||
/// <typeparam name="TStyle">Registration style.</typeparam>
|
||||
/// <typeparam name="TActivatorData">Activator data type.</typeparam>
|
||||
/// <param name="registration">The registration to configure.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<TLimit, TActivatorData, TStyle>
|
||||
InstancePerHttpRequest<TLimit, TActivatorData, TStyle>(
|
||||
this IRegistrationBuilder<TLimit, TActivatorData, TStyle> registration)
|
||||
{
|
||||
if (registration == null) throw new ArgumentNullException("registration");
|
||||
|
||||
return registration.InstancePerMatchingLifetimeScope(RequestLifetimeScopeProvider.HttpRequestTag);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register types that implement IController in the provided assemblies.
|
||||
/// </summary>
|
||||
/// <param name="builder">The container builder.</param>
|
||||
/// <param name="controllerAssemblies">Assemblies to scan for controllers.</param>
|
||||
/// <returns>Registration builder allowing the controller components to be customised.</returns>
|
||||
public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>
|
||||
RegisterControllers(
|
||||
this ContainerBuilder builder,
|
||||
params Assembly[] controllerAssemblies)
|
||||
{
|
||||
return builder.RegisterAssemblyTypes(controllerAssemblies)
|
||||
.Where(t => typeof(IController).IsAssignableFrom(t) &&
|
||||
t.Name.EndsWith("Controller", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inject an IActionInvoker into the controller's ActionInvoker property.
|
||||
/// </summary>
|
||||
/// <typeparam name="TLimit">Limit type.</typeparam>
|
||||
/// <typeparam name="TActivatorData">Activator data.</typeparam>
|
||||
/// <typeparam name="TRegistrationStyle">Registration style.</typeparam>
|
||||
/// <param name="registrationBuilder">The registration builder.</param>
|
||||
/// <returns>A registration builder.</returns>
|
||||
public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle>
|
||||
InjectActionInvoker<TLimit, TActivatorData, TRegistrationStyle>(
|
||||
this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> registrationBuilder)
|
||||
{
|
||||
return registrationBuilder.InjectActionInvoker(new TypedService(typeof(IActionInvoker)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Inject an IActionInvoker into the controller's ActionInvoker property.
|
||||
/// </summary>
|
||||
/// <typeparam name="TLimit">Limit type.</typeparam>
|
||||
/// <typeparam name="TActivatorData">Activator data.</typeparam>
|
||||
/// <typeparam name="TRegistrationStyle">Registration style.</typeparam>
|
||||
/// <param name="registrationBuilder">The registration builder.</param>
|
||||
/// <param name="actionInvokerService">Service used to resolve the action invoker.</param>
|
||||
/// <returns>A registration builder.</returns>
|
||||
public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle>
|
||||
InjectActionInvoker<TLimit, TActivatorData, TRegistrationStyle>(
|
||||
this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> 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);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the <see cref="AutofacModelBinderProvider"/>.
|
||||
/// </summary>
|
||||
/// <param name="builder">The container builder.</param>
|
||||
public static void RegisterModelBinderProvider(this ContainerBuilder builder)
|
||||
{
|
||||
if (builder == null) throw new ArgumentNullException("builder");
|
||||
|
||||
builder.RegisterType<AutofacModelBinderProvider>()
|
||||
.As<IModelBinderProvider>()
|
||||
.SingleInstance();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets a provided registration to act as an <see cref="System.Web.Mvc.IModelBinder"/>
|
||||
/// for the specified list of types.
|
||||
/// </summary>
|
||||
/// <param name="registration">
|
||||
/// The registration for the type or object instance that will act as
|
||||
/// the model binder.
|
||||
/// </param>
|
||||
/// <param name="types">
|
||||
/// The list of model <see cref="System.Type"/> for which the <paramref name="registration" />
|
||||
/// should be a model binder.
|
||||
/// </param>
|
||||
/// <typeparam name="TLimit">
|
||||
/// Registration limit type.
|
||||
/// </typeparam>
|
||||
/// <typeparam name="TActivatorData">
|
||||
/// Activator data type.
|
||||
/// </typeparam>
|
||||
/// <typeparam name="TRegistrationStyle">
|
||||
/// Registration style.
|
||||
/// </typeparam>
|
||||
/// <returns>
|
||||
/// An Autofac registration that can be modified as needed.
|
||||
/// </returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// Thrown if <paramref name="registration" /> or <paramref name="types" /> is <see langword="null" />.
|
||||
/// </exception>
|
||||
/// <exception cref="System.ArgumentException">
|
||||
/// Thrown if <paramref name="types" /> is empty or contains all <see langword="null" />
|
||||
/// values.
|
||||
/// </exception>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The declarative mechanism of registering model binders with Autofac
|
||||
/// is through use of <see cref="Autofac.Integration.Mvc.RegistrationExtensions.RegisterModelBinders"/>
|
||||
/// and the <see cref="Autofac.Integration.Mvc.ModelBinderTypeAttribute"/>.
|
||||
/// This method is an imperative alternative.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The two mechanisms are mutually exclusive. If you register a model
|
||||
/// binder using <see cref="Autofac.Integration.Mvc.RegistrationExtensions.RegisterModelBinders"/>
|
||||
/// 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Any <see langword="null" /> values provided in <paramref name="types" />
|
||||
/// will be removed prior to registration.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> AsModelBinderForTypes<TLimit, TActivatorData, TRegistrationStyle>(this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> 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<IModelBinder>().WithMetadata(AutofacModelBinderProvider.MetadataKey, typeList);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register types that implement <see cref="IModelBinder"/> in the provided assemblies
|
||||
/// and have a <see cref="Autofac.Integration.Mvc.ModelBinderTypeAttribute"/>.
|
||||
/// </summary>
|
||||
/// <param name="builder">The container builder.</param>
|
||||
/// <param name="modelBinderAssemblies">Assemblies to scan for model binders.</param>
|
||||
/// <returns>A registration builder.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// Thrown if <paramref name="builder" /> or <paramref name="modelBinderAssemblies" /> is <see langword="null" />.
|
||||
/// </exception>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The declarative mechanism of registering model binders with Autofac
|
||||
/// is through use of this method and the
|
||||
/// <see cref="Autofac.Integration.Mvc.ModelBinderTypeAttribute"/>.
|
||||
/// If you would like more imperative control over registration for your
|
||||
/// model binders, see the <see cref="AsModelBinderForTypes{TLimit,TActivatorData,TRegistrationStyle}"/>
|
||||
/// method.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The two mechanisms are mutually exclusive. If you register a model
|
||||
/// binder using <see cref="AsModelBinderForTypes{TLimit,TActivatorData,TRegistrationStyle}"/>
|
||||
/// 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This method only registers types that implement <see cref="IModelBinder"/>
|
||||
/// and are marked with the <see cref="Autofac.Integration.Mvc.ModelBinderTypeAttribute"/>.
|
||||
/// The model binder must have the attribute because the
|
||||
/// <see cref="Autofac.Integration.Mvc.AutofacModelBinderProvider"/> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// If your model is not marked with the attribute, or if you don't want
|
||||
/// to use attributes, use the
|
||||
/// <see cref="AsModelBinderForTypes{TLimit,TActivatorData,TRegistrationStyle}"/>
|
||||
/// extension instead.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static IRegistrationBuilder<object, ScanningActivatorData, DynamicRegistrationStyle>
|
||||
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<IModelBinder>()
|
||||
.InstancePerHttpRequest()
|
||||
.WithMetadata(AutofacModelBinderProvider.MetadataKey, type =>
|
||||
(from ModelBinderTypeAttribute attribute in type.GetCustomAttributes(typeof(ModelBinderTypeAttribute), true)
|
||||
from targetType in attribute.TargetTypes
|
||||
select targetType).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers the <see cref="AutofacFilterProvider"/>.
|
||||
/// </summary>
|
||||
/// <param name="builder">The container builder.</param>
|
||||
public static void RegisterFilterProvider(this ContainerBuilder builder)
|
||||
{
|
||||
if (builder == null) throw new ArgumentNullException("builder");
|
||||
|
||||
foreach (var provider in FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().ToArray())
|
||||
FilterProviders.Providers.Remove(provider);
|
||||
|
||||
builder.RegisterType<AutofacFilterProvider>()
|
||||
.As<IFilterProvider>()
|
||||
.SingleInstance();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cache instances in the web session. This implies external ownership (disposal is not
|
||||
/// available.) All dependencies must also have external ownership.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// It is strongly recommended that components cached per-session do not take dependencies on
|
||||
/// other services.
|
||||
/// </remarks>
|
||||
/// <typeparam name="TLimit">Registration limit type.</typeparam>
|
||||
/// <typeparam name="TSingleRegistrationStyle">Registration style.</typeparam>
|
||||
/// <typeparam name="TActivatorData">Activator data type.</typeparam>
|
||||
/// <param name="registration">The registration to configure.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "It is the responsibility of the registry to dispose of registrations.")]
|
||||
public static IRegistrationBuilder<TLimit, TActivatorData, TSingleRegistrationStyle>
|
||||
CacheInSession<TLimit, TActivatorData, TSingleRegistrationStyle>(
|
||||
this IRegistrationBuilder<TLimit, TActivatorData, TSingleRegistrationStyle> 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()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IActionFilter"/> for the specified controller action.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="actionSelector">The action selector.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsActionFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration,
|
||||
Expression<Action<TController>> actionSelector, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IActionFilter, TController>(registration, AutofacFilterProvider.ActionFilterMetadataKey, actionSelector, order);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IActionFilter"/> for the specified controller.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsActionFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IActionFilter, TController>(registration, AutofacFilterProvider.ActionFilterMetadataKey, order);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IAuthorizationFilter"/> for the specified controller action.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="actionSelector">The action selector.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsAuthorizationFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration,
|
||||
Expression<Action<TController>> actionSelector, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IAuthorizationFilter, TController>(registration, AutofacFilterProvider.AuthorizationFilterMetadataKey, actionSelector, order);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IAuthorizationFilter"/> for the specified controller.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsAuthorizationFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IAuthorizationFilter, TController>(registration, AutofacFilterProvider.AuthorizationFilterMetadataKey, order);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IExceptionFilter"/> for the specified controller action.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="actionSelector">The action selector.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsExceptionFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration,
|
||||
Expression<Action<TController>> actionSelector, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IExceptionFilter, TController>(registration, AutofacFilterProvider.ExceptionFilterMetadataKey, actionSelector, order);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IExceptionFilter"/> for the specified controller.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsExceptionFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IExceptionFilter, TController>(registration, AutofacFilterProvider.ExceptionFilterMetadataKey, order);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IResultFilter"/> for the specified controller action.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="actionSelector">The action selector.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsResultFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration,
|
||||
Expression<Action<TController>> actionSelector, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IResultFilter, TController>(registration, AutofacFilterProvider.ResultFilterMetadataKey, actionSelector, order);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the provided registration to act as an <see cref="IResultFilter"/> for the specified controller.
|
||||
/// </summary>
|
||||
/// <typeparam name="TController">The type of the controller.</typeparam>
|
||||
/// <param name="registration">The registration.</param>
|
||||
/// <param name="order">The order in which the filter is applied.</param>
|
||||
/// <returns>A registration builder allowing further configuration of the component.</returns>
|
||||
public static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsResultFilterFor<TController>(this IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, int order = Filter.DefaultOrder)
|
||||
where TController : IController
|
||||
{
|
||||
return AsFilterFor<IResultFilter, TController>(registration, AutofacFilterProvider.ResultFilterMetadataKey, order);
|
||||
}
|
||||
|
||||
static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsFilterFor<TFilter, TController>(IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, string metadataKey, Expression<Action<TController>> 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<TFilter>())
|
||||
{
|
||||
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<TFilter>().WithMetadata(metadataKey, metadata);
|
||||
}
|
||||
|
||||
static IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle>
|
||||
AsFilterFor<TFilter, TController>(IRegistrationBuilder<object, IConcreteActivatorData, SingleRegistrationStyle> registration, string metadataKey, int order)
|
||||
where TController : IController
|
||||
{
|
||||
if (registration == null) throw new ArgumentNullException("registration");
|
||||
|
||||
var limitType = registration.ActivatorData.Activator.LimitType;
|
||||
|
||||
if (!limitType.IsAssignableTo<TFilter>())
|
||||
{
|
||||
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<TFilter>().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;
|
||||
}
|
||||
}
|
||||
}
|
90
Autofac.Integration.Mvc/RegistrationExtensionsResources.Designer.cs
generated
Normal file
90
Autofac.Integration.Mvc/RegistrationExtensionsResources.Designer.cs
generated
Normal file
|
@ -0,0 +1,90 @@
|
|||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.18010
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace Autofac.Integration.Mvc {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
/// </summary>
|
||||
// This class was auto-generated by the StronglyTypedResourceBuilder
|
||||
// class via a tool like ResGen or Visual Studio.
|
||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
||||
// with the /str option, or rebuild your VS project.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class RegistrationExtensionsResources {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal RegistrationExtensionsResources() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the cached ResourceManager instance used by this class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Autofac.Integration.Mvc.RegistrationExtensionsResources", typeof(RegistrationExtensionsResources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the current thread's CurrentUICulture property for all
|
||||
/// resource lookups using this strongly typed resource class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to The action method Expression is invalid. It should consist only of a Method call to a controller action method..
|
||||
/// </summary>
|
||||
internal static string InvalidActionExpress {
|
||||
get {
|
||||
return ResourceManager.GetString("InvalidActionExpress", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Type list may not be empty or contain all null values..
|
||||
/// </summary>
|
||||
internal static string InvalidModelBinderType {
|
||||
get {
|
||||
return ResourceManager.GetString("InvalidModelBinderType", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to The type '{0}' must be assignable to the filter type '{1}'..
|
||||
/// </summary>
|
||||
internal static string MustBeAssignableToFilterType {
|
||||
get {
|
||||
return ResourceManager.GetString("MustBeAssignableToFilterType", resourceCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
129
Autofac.Integration.Mvc/RegistrationExtensionsResources.resx
Normal file
129
Autofac.Integration.Mvc/RegistrationExtensionsResources.resx
Normal file
|
@ -0,0 +1,129 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="InvalidActionExpress" xml:space="preserve">
|
||||
<value>The action method Expression is invalid. It should consist only of a Method call to a controller action method.</value>
|
||||
</data>
|
||||
<data name="InvalidModelBinderType" xml:space="preserve">
|
||||
<value>Type list may not be empty or contain all null values.</value>
|
||||
</data>
|
||||
<data name="MustBeAssignableToFilterType" xml:space="preserve">
|
||||
<value>The type '{0}' must be assignable to the filter type '{1}'.</value>
|
||||
</data>
|
||||
</root>
|
79
Autofac.Integration.Mvc/RequestLifetimeHttpModule.cs
Normal file
79
Autofac.Integration.Mvc/RequestLifetimeHttpModule.cs
Normal file
|
@ -0,0 +1,79 @@
|
|||
// 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.Web;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// An <see cref="IHttpModule"/> and <see cref="ILifetimeScopeProvider"/> implementation
|
||||
/// that creates a nested lifetime scope for each HTTP request.
|
||||
/// </summary>
|
||||
internal class RequestLifetimeHttpModule : IHttpModule
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the lifetime scope provider that should be notified when a HTTP request ends.
|
||||
/// </summary>
|
||||
internal static ILifetimeScopeProvider LifetimeScopeProvider { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a module and prepares it to handle requests.
|
||||
/// </summary>
|
||||
/// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the
|
||||
/// methods, properties, and events common to all application objects within an ASP.NET application</param>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// Thrown if <paramref name="context" /> is <see langword="null" />.
|
||||
/// </exception>
|
||||
public void Init(HttpApplication context)
|
||||
{
|
||||
if (context == null)
|
||||
{
|
||||
throw new ArgumentNullException("context");
|
||||
}
|
||||
context.EndRequest += OnEndRequest;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
public static void SetLifetimeScopeProvider(ILifetimeScopeProvider lifetimeScopeProvider)
|
||||
{
|
||||
if (lifetimeScopeProvider == null) throw new ArgumentNullException("lifetimeScopeProvider");
|
||||
|
||||
LifetimeScopeProvider = lifetimeScopeProvider;
|
||||
}
|
||||
|
||||
static void OnEndRequest(object sender, EventArgs e)
|
||||
{
|
||||
if (LifetimeScopeProvider != null)
|
||||
LifetimeScopeProvider.EndLifetimeScope();
|
||||
}
|
||||
}
|
||||
}
|
122
Autofac.Integration.Mvc/RequestLifetimeScopeProvider.cs
Normal file
122
Autofac.Integration.Mvc/RequestLifetimeScopeProvider.cs
Normal file
|
@ -0,0 +1,122 @@
|
|||
// This software is part of the Autofac IoC container
|
||||
// Copyright (c) 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.Web;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates and disposes HTTP request based lifetime scopes.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The provider is notified when a HTTP request ends by the <see cref="RequestLifetimeHttpModule"/>.
|
||||
/// </remarks>
|
||||
public class RequestLifetimeScopeProvider : ILifetimeScopeProvider
|
||||
{
|
||||
readonly ILifetimeScope _container;
|
||||
|
||||
/// <summary>
|
||||
/// Tag used to identify registrations that are scoped to the HTTP request level.
|
||||
/// </summary>
|
||||
internal static readonly object HttpRequestTag = "AutofacWebRequest";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RequestLifetimeScopeProvider"/> class.
|
||||
/// </summary>
|
||||
/// <param name="container">The parent container, usually the application container.</param>
|
||||
public RequestLifetimeScopeProvider(ILifetimeScope container)
|
||||
{
|
||||
if (container == null) throw new ArgumentNullException("container");
|
||||
_container = container;
|
||||
RequestLifetimeHttpModule.SetLifetimeScopeProvider(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the global, application-wide container.
|
||||
/// </summary>
|
||||
public ILifetimeScope ApplicationContainer
|
||||
{
|
||||
get { return _container; }
|
||||
}
|
||||
|
||||
static ILifetimeScope LifetimeScope
|
||||
{
|
||||
get { return (ILifetimeScope)HttpContext.Current.Items[typeof(ILifetimeScope)]; }
|
||||
set { HttpContext.Current.Items[typeof(ILifetimeScope)] = value; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a nested lifetime scope that services can be resolved from.
|
||||
/// </summary>
|
||||
/// <param name="configurationAction">
|
||||
/// A configuration action that will execute during lifetime scope creation.
|
||||
/// </param>
|
||||
/// <returns>A new or existing nested lifetime scope.</returns>
|
||||
public ILifetimeScope GetLifetimeScope(Action<ContainerBuilder> configurationAction)
|
||||
{
|
||||
if (HttpContext.Current == null)
|
||||
{
|
||||
throw new InvalidOperationException(RequestLifetimeScopeProviderResources.HttpContextNotAvailable);
|
||||
}
|
||||
|
||||
if (LifetimeScope == null)
|
||||
{
|
||||
if ((LifetimeScope = GetLifetimeScopeCore(configurationAction)) == null)
|
||||
throw new InvalidOperationException(
|
||||
string.Format(CultureInfo.CurrentCulture, RequestLifetimeScopeProviderResources.NullLifetimeScopeReturned, GetType().FullName));
|
||||
}
|
||||
return LifetimeScope;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ends the current HTTP request lifetime scope.
|
||||
/// </summary>
|
||||
public void EndLifetimeScope()
|
||||
{
|
||||
var lifetimeScope = LifetimeScope;
|
||||
if (lifetimeScope != null)
|
||||
lifetimeScope.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a lifetime scope for the current HTTP request. This method can be overridden
|
||||
/// to alter the way that the life time scope is constructed.
|
||||
/// </summary>
|
||||
/// <param name="configurationAction">
|
||||
/// A configuration action that will execute during lifetime scope creation.
|
||||
/// </param>
|
||||
/// <returns>A new lifetime scope for the current HTTP request.</returns>
|
||||
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
|
||||
protected virtual ILifetimeScope GetLifetimeScopeCore(Action<ContainerBuilder> configurationAction)
|
||||
{
|
||||
return (configurationAction == null)
|
||||
? ApplicationContainer.BeginLifetimeScope(HttpRequestTag)
|
||||
: ApplicationContainer.BeginLifetimeScope(HttpRequestTag, configurationAction);
|
||||
}
|
||||
}
|
||||
}
|
81
Autofac.Integration.Mvc/RequestLifetimeScopeProviderResources.Designer.cs
generated
Normal file
81
Autofac.Integration.Mvc/RequestLifetimeScopeProviderResources.Designer.cs
generated
Normal file
|
@ -0,0 +1,81 @@
|
|||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.1
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace Autofac.Integration.Mvc {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
/// </summary>
|
||||
// This class was auto-generated by the StronglyTypedResourceBuilder
|
||||
// class via a tool like ResGen or Visual Studio.
|
||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
||||
// with the /str option, or rebuild your VS project.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class RequestLifetimeScopeProviderResources {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal RequestLifetimeScopeProviderResources() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the cached ResourceManager instance used by this class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Autofac.Integration.Mvc.RequestLifetimeScopeProviderResources", typeof(RequestLifetimeScopeProviderResources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the current thread's CurrentUICulture property for all
|
||||
/// resource lookups using this strongly typed resource class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to The request lifetime scope cannot be created because the HttpContext is not available..
|
||||
/// </summary>
|
||||
internal static string HttpContextNotAvailable {
|
||||
get {
|
||||
return ResourceManager.GetString("HttpContextNotAvailable", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to The 'GetLifetimeScopeCore' method implementation on '{0}' returned a null ILifetimeScope instance. When overridden this method must return a valid ILifetimeScope instance for the current HTTP request..
|
||||
/// </summary>
|
||||
internal static string NullLifetimeScopeReturned {
|
||||
get {
|
||||
return ResourceManager.GetString("NullLifetimeScopeReturned", resourceCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,126 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="HttpContextNotAvailable" xml:space="preserve">
|
||||
<value>The request lifetime scope cannot be created because the HttpContext is not available.</value>
|
||||
</data>
|
||||
<data name="NullLifetimeScopeReturned" xml:space="preserve">
|
||||
<value>The 'GetLifetimeScopeCore' method implementation on '{0}' returned a null ILifetimeScope instance. When overridden this method must return a valid ILifetimeScope instance for the current HTTP request.</value>
|
||||
</data>
|
||||
</root>
|
78
Autofac.Integration.Mvc/ViewRegistrationSource.cs
Normal file
78
Autofac.Integration.Mvc/ViewRegistrationSource.cs
Normal file
|
@ -0,0 +1,78 @@
|
|||
// 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.Collections.Generic;
|
||||
using System.Web.Mvc;
|
||||
using Autofac.Builder;
|
||||
using Autofac.Core;
|
||||
|
||||
namespace Autofac.Integration.Mvc
|
||||
{
|
||||
/// <summary>
|
||||
/// A registration source for building view registrations.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Supports view registrations for <see cref="WebViewPage"/>, <see cref="ViewPage"/>,
|
||||
/// <see cref="ViewMasterPage"/> and <see cref="ViewUserControl"/> derived types.
|
||||
/// </remarks>
|
||||
public class ViewRegistrationSource : IRegistrationSource
|
||||
{
|
||||
/// <summary>
|
||||
/// Retrieve registrations for an unregistered service, to be used
|
||||
/// by the container.
|
||||
/// </summary>
|
||||
/// <param name="service">The service that was requested.</param>
|
||||
/// <param name="registrationAccessor">A function that will return existing registrations for a service.</param>
|
||||
/// <returns>Registrations providing the service.</returns>
|
||||
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
|
||||
{
|
||||
var typedService = service as IServiceWithType;
|
||||
|
||||
if (typedService != null && IsSupportedView(typedService.ServiceType))
|
||||
yield return RegistrationBuilder.ForType(typedService.ServiceType)
|
||||
.PropertiesAutowired()
|
||||
.InstancePerDependency()
|
||||
.CreateRegistration();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the registrations provided by this source are 1:1 adapters on top
|
||||
/// of other components (I.e. like Meta, Func or Owned.)
|
||||
/// </summary>
|
||||
public bool IsAdapterForIndividualComponents
|
||||
{
|
||||
get { return false; }
|
||||
}
|
||||
|
||||
static bool IsSupportedView(Type serviceType)
|
||||
{
|
||||
return serviceType.IsAssignableTo<WebViewPage>()
|
||||
|| serviceType.IsAssignableTo<ViewPage>()
|
||||
|| serviceType.IsAssignableTo<ViewMasterPage>()
|
||||
|| serviceType.IsAssignableTo<ViewUserControl>();
|
||||
}
|
||||
}
|
||||
}
|
8
Autofac.Integration.Mvc/packages.config
Normal file
8
Autofac.Integration.Mvc/packages.config
Normal file
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Autofac" version="3.0.1" targetFramework="net40" />
|
||||
<package id="Microsoft.AspNet.Mvc" version="4.0.20710.0" targetFramework="net40" />
|
||||
<package id="Microsoft.AspNet.Razor" version="2.0.20715.0" targetFramework="net40" />
|
||||
<package id="Microsoft.AspNet.WebPages" version="2.0.20710.0" targetFramework="net40" />
|
||||
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net40" />
|
||||
</packages>
|
Loading…
Add table
Add a link
Reference in a new issue