Skip to content

Commit

Permalink
Merge pull request #11 from Velir/issue-8
Browse files Browse the repository at this point in the history
Fixed PerRequest dependency resolution in pipeline processor context
  • Loading branch information
smithc committed Feb 22, 2016
2 parents 889ace0 + 616f8a5 commit 3fb89cb
Show file tree
Hide file tree
Showing 17 changed files with 259 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@
<Reference Include="Autofac">
<HintPath>..\packages\Autofac.3.5.2\lib\net40\Autofac.dll</HintPath>
</Reference>
<Reference Include="Autofac.Integration.Mvc, Version=3.3.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
<HintPath>..\packages\Autofac.Mvc5.3.3.3\lib\net45\Autofac.Integration.Mvc.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Castle.Core">
<HintPath>..\packages\Castle.Core.3.3.3\lib\net45\Castle.Core.dll</HintPath>
</Reference>
Expand Down Expand Up @@ -103,6 +107,7 @@
<Compile Include="Models\Factory\AutofacViewModelFactory.cs" />
<Compile Include="Models\GlassViewModel.cs" />
<Compile Include="Models\InjectableGlassViewModelBase.cs" />
<Compile Include="Pipelines\Factories\Providers\MvcLifetimeScopeProvider.cs" />
<Compile Include="Pipelines\Processors\GetModelFromViewProcessor.cs" />
<Compile Include="Pipelines\Processors\GetModelProcessor.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
Expand All @@ -127,6 +132,7 @@
<Name>Jabberwocky.Glass</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Autofac;
using Autofac.Integration.Mvc;
using ILifetimeScopeProvider = Jabberwocky.Glass.Autofac.Pipelines.Factories.Providers.ILifetimeScopeProvider;

namespace Jabberwocky.Glass.Autofac.Mvc.Pipelines.Factories.Providers
{
public class MvcLifetimeScopeProvider : ILifetimeScopeProvider
{
public ILifetimeScope GetLifetimeScope()
{
return AutofacDependencyResolver.Current?.RequestLifetimeScope;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public GetModelFromViewProcessor(IModelCacheManager modelCacheManager, IViewMode
/// </value>
public string ContextName { get; set; }

protected override void Run(GetModelArgs args)
protected internal override void Run(GetModelArgs args)
{
if (!IsValidForProcessing(args))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public GetModelProcessor(IViewModelFactory viewModelFactory)
_viewModelFactory = viewModelFactory;
}

protected override void Run(GetModelArgs args)
protected internal override void Run(GetModelArgs args)
{
if (args.Result != null) return;

Expand Down
1 change: 1 addition & 0 deletions Jabberwocky.Glass.Autofac.Mvc/packages.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Autofac" version="3.5.2" targetFramework="net45" />
<package id="Autofac.Mvc5" version="3.3.3" targetFramework="net45" />
<package id="Castle.Core" version="3.3.3" targetFramework="net45" />
<package id="Glass.Mapper.Sc" version="4.0.3.51" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{86B4E810-DCA7-4510-BA2B-EC1DDA9CB7FE}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Jabberwocky.Glass.Autofac.WebApi</RootNamespace>
<AssemblyName>Jabberwocky.Glass.Autofac.WebApi</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</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>
</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>
</PropertyGroup>
<ItemGroup>
<Reference Include="Autofac, Version=3.5.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
<HintPath>..\packages\Autofac.3.5.2\lib\net40\Autofac.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Autofac.Integration.WebApi, Version=3.3.0.0, Culture=neutral, PublicKeyToken=17863af14b0044da, processorArchitecture=MSIL">
<HintPath>..\packages\Autofac.WebApi2.3.3.3\lib\net45\Autofac.Integration.WebApi.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Pipelines\Factories\Providers\WebApiLifetimeScopeProvider.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Jabberwocky.Glass.Autofac\Jabberwocky.Glass.Autofac.csproj">
<Project>{ea620f62-8d08-4031-bac4-1c60d5c5cbc9}</Project>
<Name>Jabberwocky.Glass.Autofac</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.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>
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Web.Http;
using System.Web.Http.Dependencies;
using Autofac;
using Autofac.Integration.WebApi;
using Jabberwocky.Glass.Autofac.Pipelines.Factories.Providers;

namespace Jabberwocky.Glass.Autofac.WebApi.Pipelines.Factories.Providers
{
public class WebApiLifetimeScopeProvider : ILifetimeScopeProvider
{
public ILifetimeScope GetLifetimeScope()
{
// If using the Autofac.WebApi integration package, this dependency should be of type 'AutofacWebApiDependencyResolver'
var resolver = GlobalConfiguration.Configuration.DependencyResolver as IDependencyScope;

return resolver?.GetRequestLifetimeScope();
}
}
}
36 changes: 36 additions & 0 deletions Jabberwocky.Glass.Autofac.WebApi/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Jabberwocky.Glass.Autofac.WebApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Jabberwocky.Glass.Autofac.WebApi")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("86b4e810-dca7-4510-ba2b-ec1dda9cb7fe")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
9 changes: 9 additions & 0 deletions Jabberwocky.Glass.Autofac.WebApi/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Autofac" version="3.5.2" targetFramework="net45" />
<package id="Autofac.WebApi2" version="3.3.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />
</packages>
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Autofac;
using Jabberwocky.Glass.Autofac.Pipelines.Factories;
using Jabberwocky.Glass.Autofac.Pipelines.Factories.Providers;
using Jabberwocky.Glass.Autofac.Pipelines.Processors;

namespace Jabberwocky.Glass.Autofac.Extensions
Expand All @@ -14,6 +17,7 @@ public static class SitecorePipelineRegistrationExtensions
private const string MasterDatabaseName = "master";

private const string JabberwockyMvcDll = "Jabberwocky.Glass.Autofac.Mvc";
private const string JabberwockyWebApiDll = "Jabberwocky.Glass.Autofac.WebApi";

/// <summary>
/// Registers any custom Sitecore Pipeline Processors that implement the IProcessor interface
Expand All @@ -38,10 +42,15 @@ public static ContainerBuilder RegisterProcessors(this ContainerBuilder builder,
/// </returns>
public static ContainerBuilder RegisterProcessors(this ContainerBuilder builder, params Assembly[] assemblies)
{
var asm = new[] {TryLoadAssembly(JabberwockyMvcDll)}.Concat(assemblies).Where(a => a != null).Distinct().ToArray();
var asm = new[] { JabberwockyMvcDll, JabberwockyWebApiDll }.Select(TryLoadAssembly).Concat(assemblies).Where(a => a != null).Distinct().ToArray();

// Register processors
builder.RegisterAssemblyTypes(asm).AsClosedTypesOf(typeof(IProcessor<>));


// Register internals for Lifetime Scope resolution
builder.RegisterAssemblyTypes(asm).AssignableTo<ILifetimeScopeProvider>().As<ILifetimeScopeProvider>();
builder.Register(c => new DefaultLifetimeScopeFactory(c.Resolve<IEnumerable<ILifetimeScopeProvider>>())).As<ILifetimeScopeFactory>();

return builder;
}

Expand Down
3 changes: 3 additions & 0 deletions Jabberwocky.Glass.Autofac/Jabberwocky.Glass.Autofac.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@
<Compile Include="Glass\LazyObjectInterceptor.cs" />
<Compile Include="Glass\Tasks\AutofacGlassContructorTask.cs" />
<Compile Include="Pipelines\Factories\AutofacProcessorFactory.cs" />
<Compile Include="Pipelines\Factories\DefaultLifetimeScopeFactory.cs" />
<Compile Include="Pipelines\Factories\ILifetimeScopeFactory.cs" />
<Compile Include="Pipelines\Factories\Providers\ILifetimeScopeProvider.cs" />
<Compile Include="Pipelines\Processors\ProcessorLifetimeBase.cs" />
<Compile Include="Pipelines\Processors\ProcessorBase.cs" />
<Compile Include="Pipelines\Processors\IProcessor.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ public class AutofacProcessorFactory : IFactory
{
protected static IContainer Container => AutofacConfig.ServiceLocator;

public virtual object GetObject(string identifier)
public virtual object GetObject(string identifier)
{
var type = ResolveType(identifier);
if (type == null) return null;

// Includes Pipeline specific registrations that override existing defaults
var scope = Container.BeginLifetimeScope(ConfigureRegistrationOverrides);
var scope = CreateLifetimeScope();
try
{
var processor = scope.Resolve(type);
Expand All @@ -43,6 +43,20 @@ public virtual object GetObject(string identifier)
return null;
}

protected virtual ILifetimeScope CreateLifetimeScope()
{
if (Container == null)
throw new InvalidOperationException($"The '{nameof(Container)}' property was null. Ensure that the AutofacConfig.{nameof(AutofacConfig.ServiceLocator)} has been assigned.");

using (var scope = Container.BeginLifetimeScope())
{
var existingScopeProvider = scope.ResolveOptional<ILifetimeScopeFactory>();
var scopeResolver = existingScopeProvider?.GetCurrentLifetimeScope() ?? Container;

return scopeResolver.BeginLifetimeScope(ConfigureRegistrationOverrides);
}
}

protected virtual void ConfigureRegistrationOverrides(ContainerBuilder builder)
{
builder.RegisterSitecorePipelineServices();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using Jabberwocky.Glass.Autofac.Pipelines.Factories.Providers;

namespace Jabberwocky.Glass.Autofac.Pipelines.Factories
{
internal class DefaultLifetimeScopeFactory : ILifetimeScopeFactory
{
private readonly IEnumerable<ILifetimeScopeProvider> _scopeProviders;

internal DefaultLifetimeScopeFactory(IEnumerable<ILifetimeScopeProvider> scopeProviders)
{
if (scopeProviders == null) throw new ArgumentNullException(nameof(scopeProviders));
_scopeProviders = scopeProviders;
}

public ILifetimeScope GetCurrentLifetimeScope()
{
return _scopeProviders
.Select(provider => provider.GetLifetimeScope())
.FirstOrDefault(scope => scope != null);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using Autofac;

namespace Jabberwocky.Glass.Autofac.Pipelines.Factories
{
public interface ILifetimeScopeFactory
{
ILifetimeScope GetCurrentLifetimeScope();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using Autofac;

namespace Jabberwocky.Glass.Autofac.Pipelines.Factories.Providers
{
internal interface ILifetimeScopeProvider
{
ILifetimeScope GetLifetimeScope();
}
}
3 changes: 3 additions & 0 deletions Jabberwocky.Glass.Autofac/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]

[assembly: InternalsVisibleTo("Jabberwocky.Glass.Autofac.Mvc")]
[assembly: InternalsVisibleTo("Jabberwocky.Glass.Autofac.WebApi")]
9 changes: 8 additions & 1 deletion Jabberwocky.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.23107.0
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jabberwocky.Core", "Jabberwocky.Core\Jabberwocky.Core.csproj", "{79F22272-B90E-4461-BAEE-92AE1A6C28BC}"
EndProject
Expand Down Expand Up @@ -56,6 +56,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extras", "Extras", "{338A9D
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jabberwocky.Autofac.Extras.MiniProfiler", "Jabberwocky.Autofac.Extras.MiniProfiler\Jabberwocky.Autofac.Extras.MiniProfiler.csproj", "{44DB88AB-C38E-4CAE-ADA0-BC64778A1D4A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jabberwocky.Glass.Autofac.WebApi", "Jabberwocky.Glass.Autofac.WebApi\Jabberwocky.Glass.Autofac.WebApi.csproj", "{86B4E810-DCA7-4510-BA2B-EC1DDA9CB7FE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -130,6 +132,10 @@ Global
{44DB88AB-C38E-4CAE-ADA0-BC64778A1D4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{44DB88AB-C38E-4CAE-ADA0-BC64778A1D4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{44DB88AB-C38E-4CAE-ADA0-BC64778A1D4A}.Release|Any CPU.Build.0 = Release|Any CPU
{86B4E810-DCA7-4510-BA2B-EC1DDA9CB7FE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{86B4E810-DCA7-4510-BA2B-EC1DDA9CB7FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{86B4E810-DCA7-4510-BA2B-EC1DDA9CB7FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{86B4E810-DCA7-4510-BA2B-EC1DDA9CB7FE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -155,5 +161,6 @@ Global
{315DCFFB-97B4-43E5-9ECF-3EDC7E32C93F} = {FF1D41BA-5DE4-49CC-8CFF-08B1BF700C3D}
{338A9D71-3ED1-4E69-AC1B-E5033846B3A4} = {FF1D41BA-5DE4-49CC-8CFF-08B1BF700C3D}
{44DB88AB-C38E-4CAE-ADA0-BC64778A1D4A} = {338A9D71-3ED1-4E69-AC1B-E5033846B3A4}
{86B4E810-DCA7-4510-BA2B-EC1DDA9CB7FE} = {FF1D41BA-5DE4-49CC-8CFF-08B1BF700C3D}
EndGlobalSection
EndGlobal

0 comments on commit 3fb89cb

Please sign in to comment.