Skip to content

Commit

Permalink
Merge pull request #40 from JakeGinnivan/AutofacConventions
Browse files Browse the repository at this point in the history
Added autofac package
  • Loading branch information
JakeGinnivan committed Sep 28, 2013
2 parents a834921 + 6f6823c commit 6b16512
Show file tree
Hide file tree
Showing 20 changed files with 13,769 additions and 45 deletions.
1 change: 1 addition & 0 deletions ConventionTests.proj
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,6 @@
</PropertyGroup>
<MakeDir Directories="$(Root)build\Artifacts" />
<Exec Command="@(NuGet) pack $(Root)TestStack.ConventionTests\TestStack.ConventionTests.nuspec -Version $(Version) -OutputDir $(Root)build\Artifacts -BasePath $(Root)TestStack.ConventionTests\bin\$(Configuration)" />
<Exec Command="@(NuGet) pack $(Root)TestStack.ConventionTests.Autofac\TestStack.ConventionTests.Autofac.nuspec -Version $(Version) -OutputDir $(Root)build\Artifacts -BasePath $(Root)TestStack.ConventionTests.Autofac\bin\$(Configuration)" />
</Target>
</Project>
8 changes: 7 additions & 1 deletion ConventionTests.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 2013
VisualStudioVersion = 12.0.20623.1 VSUPREVIEW
VisualStudioVersion = 12.0.20827.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConventionTests", "ConventionTests\ConventionTests.csproj", "{1E12EA0C-9182-4029-991A-B0B9D38F5783}"
EndProject
Expand Down Expand Up @@ -29,6 +29,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleApp.Tests", "SampleAp
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleApp", "SampleApp\SampleApp.csproj", "{56467A5A-7DD6-45B3-A84C-144A3C5D0C7A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestStack.ConventionTests.Autofac", "TestStack.ConventionTests.Autofac\TestStack.ConventionTests.Autofac.csproj", "{A747FD64-5338-4572-879D-A9DEB00EBD56}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -59,6 +61,10 @@ Global
{56467A5A-7DD6-45B3-A84C-144A3C5D0C7A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{56467A5A-7DD6-45B3-A84C-144A3C5D0C7A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{56467A5A-7DD6-45B3-A84C-144A3C5D0C7A}.Release|Any CPU.Build.0 = Release|Any CPU
{A747FD64-5338-4572-879D-A9DEB00EBD56}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A747FD64-5338-4572-879D-A9DEB00EBD56}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A747FD64-5338-4572-879D-A9DEB00EBD56}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A747FD64-5338-4572-879D-A9DEB00EBD56}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
83 changes: 83 additions & 0 deletions TestStack.ConventionTests.Autofac/AutofacRegistrations.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
namespace TestStack.ConventionTests.Autofac
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using global::Autofac.Core;
using global::Autofac.Core.Activators.Delegate;
using global::Autofac.Core.Activators.ProvidedInstance;
using global::Autofac.Core.Activators.Reflection;
using global::Autofac.Core.Lifetime;

public class AutofacRegistrations : IConventionData
{
private readonly IComponentRegistry componentRegistry;

public AutofacRegistrations(IComponentRegistry componentRegistry)
{
this.componentRegistry = componentRegistry;
}

public string Description
{
get { return "All AutofacContainer Registrations"; }
}

public bool HasData
{
get { return true; }
}

public IComponentRegistry ComponentRegistry
{
get { return componentRegistry; }
}

public Type GetConcreteType(IComponentRegistration r)
{
var reflectionActivator = r.Activator as ReflectionActivator;
if (reflectionActivator != null) return reflectionActivator.LimitType;

var delegateActivator = r.Activator as DelegateActivator;
if (delegateActivator != null) return delegateActivator.LimitType;

var providedInstanceActivator = r.Activator as ProvidedInstanceActivator;
if (providedInstanceActivator != null) return providedInstanceActivator.LimitType;

throw new InvalidOperationException(r.Activator.GetType() + " is not a known component registration type");
}

public Lifetime GetLifetime(IComponentRegistration componentRegistration)
{
if (componentRegistration.Ownership == InstanceOwnership.OwnedByLifetimeScope && componentRegistration.Sharing == InstanceSharing.Shared &&
componentRegistration.Lifetime is RootScopeLifetime)
return Lifetime.SingleInstance;
if (componentRegistration.Ownership == InstanceOwnership.OwnedByLifetimeScope && componentRegistration.Sharing == InstanceSharing.Shared &&
componentRegistration.Lifetime is CurrentScopeLifetime)
return Lifetime.InstancePerLifetimeScope;
if (componentRegistration.Ownership == InstanceOwnership.OwnedByLifetimeScope && componentRegistration.Sharing == InstanceSharing.None &&
componentRegistration.Lifetime is CurrentScopeLifetime)
return Lifetime.Transient;
if (componentRegistration.Ownership == InstanceOwnership.ExternallyOwned && componentRegistration.Sharing == InstanceSharing.None &&
componentRegistration.Lifetime is CurrentScopeLifetime)
return Lifetime.ExternallyOwned;
if (componentRegistration.Ownership == InstanceOwnership.ExternallyOwned && componentRegistration.Sharing == InstanceSharing.Shared &&
componentRegistration.Lifetime is CurrentScopeLifetime)
return Lifetime.SingleInstanceExternallyOwned;

throw new InvalidOperationException(string.Format("Unknown registration type for {3} Ownership: {0}, Sharing: {1}, Lifetime type: {2}", componentRegistration.Ownership, componentRegistration.Sharing,
componentRegistration.Lifetime.GetType().Name, GetConcreteType(componentRegistration)));
}

public IEnumerable<ParameterInfo> GetRegistrationCtorParameters(IComponentRegistration componentRegistration)
{
var activator = componentRegistration.Activator as ReflectionActivator;
if (activator == null)
return Enumerable.Empty<ParameterInfo>();

var limitType = activator.LimitType;
return activator.ConstructorFinder.FindConstructors(limitType).SelectMany(ctor => ctor.GetParameters());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
namespace TestStack.ConventionTests.Autofac
{
using System;
using System.Collections.Generic;
using System.Linq;
using global::Autofac;
using global::Autofac.Core;

public class CanResolveAllRegisteredServices : IConvention<AutofacRegistrations>
{
private readonly IContainer container;

public CanResolveAllRegisteredServices(IContainer container)
{
this.container = container;
}

public void Execute(AutofacRegistrations data, IConventionResultContext result)
{
var distinctTypes = data.ComponentRegistry.Registrations
.SelectMany(r => r.Services.OfType<TypedService>().Select(s => s.ServiceType).Union(GetGenericFactoryTypes(data, r)))
.Distinct();

var failingTypes = new List<Type>();
foreach (var distinctType in distinctTypes)
{
object resolvedInstance;
if (!container.TryResolve(distinctType, out resolvedInstance))
failingTypes.Add(distinctType);
}

result.Is("Can resolve all types registered with Autofac", failingTypes);
}

private IEnumerable<Type> GetGenericFactoryTypes(AutofacRegistrations data, IComponentRegistration componentRegistration)
{
return from ctorParameter in data.GetRegistrationCtorParameters(componentRegistration)
where ctorParameter.ParameterType.FullName.StartsWith("System.Func")
select ctorParameter.ParameterType.GetGenericArguments()[0];
}
}
}
14 changes: 14 additions & 0 deletions TestStack.ConventionTests.Autofac/Lifetime.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace TestStack.ConventionTests.Autofac
{
/// <summary>
/// Ordered by logical dependency precendence. Higher values should not reference lower
/// </summary>
public enum Lifetime
{
Transient = 0,
InstancePerLifetimeScope = 1,
SingleInstance = 2,
ExternallyOwned = 3,
SingleInstanceExternallyOwned = 4
}
}
36 changes: 36 additions & 0 deletions TestStack.ConventionTests.Autofac/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("TestStack.ConventionTests.Autofac")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestStack.ConventionTests.Autofac")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("97020754-a2a1-4ea8-87d4-964795d79d3f")]

// 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")]
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
namespace TestStack.ConventionTests.Autofac
{
using System.Collections.Generic;
using global::Autofac.Core;
using TestStack.ConventionTests.ConventionData;

public class ServicesShouldOnlyHaveDependenciesWithLesserLifetime : IConvention<AutofacRegistrations>
{
public void Execute(AutofacRegistrations data, IConventionResultContext result)
{
var exceptions = new List<string>();
foreach (var registration in data.ComponentRegistry.Registrations)
{
var registrationLifetime = data.GetLifetime(registration);

foreach (var ctorParameter in data.GetRegistrationCtorParameters(registration))
{
IComponentRegistration parameterRegistration;
var typedService = new TypedService(ctorParameter.ParameterType);

// If the parameter is not registered with autofac, ignore
if (!data.ComponentRegistry.TryGetRegistration(typedService, out parameterRegistration)) continue;

var parameterLifetime = data.GetLifetime(parameterRegistration);

if (parameterLifetime >= registrationLifetime) continue;

var typeName = data.GetConcreteType(registration).ToTypeNameString();
var parameterType = ctorParameter.ParameterType.ToTypeNameString();

var error = string.Format("{0} ({1}) => {2} ({3})",
typeName, registrationLifetime,
parameterType, parameterLifetime);
exceptions.Add(error);
}
}

result.Is("Components should not depend on with greater lifetimes", exceptions);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.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>{A747FD64-5338-4572-879D-A9DEB00EBD56}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TestStack.ConventionTests.Autofac</RootNamespace>
<AssemblyName>TestStack.ConventionTests.Autofac</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">
<HintPath>..\packages\Autofac.3.1.1\lib\net40\Autofac.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AutofacRegistrations.cs" />
<Compile Include="CanResolveAllRegisteredServices.cs" />
<Compile Include="Lifetime.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ServicesShouldOnlyHaveDependenciesWithLesserLifetime.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
<None Include="TestStack.ConventionTests.Autofac.nuspec" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\TestStack.ConventionTests\TestStack.ConventionTests.csproj">
<Project>{955B0236-089F-434D-BA02-63A1E24C2B7C}</Project>
<Name>TestStack.ConventionTests</Name>
</ProjectReference>
</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,22 @@
<ProjectConfiguration>
<CopyReferencedAssembliesToWorkspace>false</CopyReferencedAssembliesToWorkspace>
<ConsiderInconclusiveTestsAsPassing>false</ConsiderInconclusiveTestsAsPassing>
<PreloadReferencedAssemblies>false</PreloadReferencedAssemblies>
<AllowDynamicCodeContractChecking>true</AllowDynamicCodeContractChecking>
<AllowStaticCodeContractChecking>false</AllowStaticCodeContractChecking>
<IgnoreThisComponentCompletely>false</IgnoreThisComponentCompletely>
<RunPreBuildEvents>false</RunPreBuildEvents>
<RunPostBuildEvents>false</RunPostBuildEvents>
<PreviouslyBuiltSuccessfully>true</PreviouslyBuiltSuccessfully>
<InstrumentAssembly>true</InstrumentAssembly>
<PreventSigningOfAssembly>false</PreventSigningOfAssembly>
<AnalyseExecutionTimes>true</AnalyseExecutionTimes>
<IncludeStaticReferencesInWorkspace>true</IncludeStaticReferencesInWorkspace>
<DefaultTestTimeout>60000</DefaultTestTimeout>
<UseBuildConfiguration />
<UseBuildPlatform />
<ProxyProcessPath />
<UseCPUArchitecture>AutoDetect</UseCPUArchitecture>
<MSTestThreadApartmentState>STA</MSTestThreadApartmentState>
<BuildProcessArchitecture>x86</BuildProcessArchitecture>
</ProjectConfiguration>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0"?>
<package >
<metadata>
<version>$version$</version>
<authors>Krzysztof Kozmic, Jake Ginnivan</authors>
<owners>Krzysztof Kozmic, Jake Ginnivan</owners>
<id>TestStack.ConventionTests.Autofac</id>
<title>TestStack.ConventionTests.Autofac</title>
<tags>xunit nunit convention testing documentation autofac</tags>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>Simple convention-tester</description>
<summary>A selection of pre-packaged conventions to validate autofac</summary>
<projectUrl>https://github.com/TestStack/ConventionTests</projectUrl>
<licenseUrl>https://github.com/TestStack/ConventionTests/blob/master/license.txt</licenseUrl>
<dependencies>
<dependency id="TestStack.ConventionTests" />
<dependency id="Autofac" />
</dependencies>
</metadata>
<files>
<file src="TestStack.ConventionTests.Autofac.dll" target="lib\net40" />
<file src="TestStack.ConventionTests.Autofac.pdb" target="lib\net40" />
</files>
</package>
4 changes: 4 additions & 0 deletions TestStack.ConventionTests.Autofac/packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Autofac" version="3.1.1" targetFramework="net45" />
</packages>
Loading

0 comments on commit 6b16512

Please sign in to comment.