Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Added support to keep and resolve aspects from IoC container #14

Merged
merged 3 commits into from
Sep 29, 2011
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 4 additions & 3 deletions Snap.Autofac/AutofacAspectModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,12 @@ private static void RegistrationActivating(object sender, ActivatingEventArgs<ob
// registration context. Otherwise calling e.Context.Resolve<IInterceptor> will fail when
// the code below executes.

// for master proxy we need to assign reference to current container,
// Common service locator is used for MasterProxy to be container-agnostic
// Master proxy then uses the container to resolve interceptor instances from
if(e.Instance is MasterProxy)
{
// for master proxy we need to assign reference to current container, which is used to resolve aspects from
// AutofacServiceLocatorAdapter cannot be built just with e.Context despite fact that e.Context is of IComponentContext
// e.Context is valid only in scope of current instance activation
// To get valid IComponentContext we need to resolve it in the following way
((MasterProxy) e.Instance).Container = new AutofacServiceLocatorAdapter(e.Context.Resolve<IComponentContext>());
return;
}
Expand Down
30 changes: 26 additions & 4 deletions Snap.Autofac/AutofacServiceLocatorAdapter.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
/*
Snap v1.0

Copyright (c) 2010 Tyler Brinks

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;
using System.Collections.Generic;
Expand All @@ -14,15 +37,15 @@ namespace Snap.Autofac
/// AutofacContrib.CommonServiceLocator library, which is redistributed as a part of AutofacContrib, cannot be used.
/// Unfortunately, Autofac.CommonServiceLocator which is compatible with Autofac 2.4.5.724 is build for NET 4.0 runtime
/// This makes impossible to use it under NET 3.5 runtime.
///
/// See Issue 288: No Autofac-Contrib 2.4.3-700 release for .net 3.5
/// http://code.google.com/p/autofac/issues/detail?id=288#c2
///
/// The most recent Autofac.CommonServiceLocator, which is built for NET3.5 runtime, is of version 2.3.2.
/// See http://code.google.com/p/autofac/downloads/detail?name=AutofacContrib-2.3.2.632-NET35.zip&can=1&q=
/// But it has a reference to Autofac 2.3.2.632. Both assemblies have strong name.
/// Thus, it requires assembly version redirection to use 2.4.5.724.
/// But it has a reference to Autofac 2.3.2.632.
///
/// All described above is too complicated. It is much simple to write custom autofac service locator adapter (few lines of code).
/// It is much simple to write custom autofac service locator adapter with a just few lines of code.
/// Once Autofac.CommonServiceLocator is redistributed for NET35 runtime, switch using it instead of this class.
/// </remarks>
public class AutofacServiceLocatorAdapter : ServiceLocatorImplBase
Expand All @@ -44,7 +67,6 @@ protected override object DoGetInstance(Type serviceType, string key)
protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
{
var enumerableType = typeof(IEnumerable<>).MakeGenericType(serviceType);

return ((IEnumerable)_container.Resolve(enumerableType)).Cast<object>();
}
}
Expand Down
25 changes: 24 additions & 1 deletion Snap.CastleWindsor/WindsorServiceLocatorAdapter.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
/*
Snap v1.0

Copyright (c) 2010 Tyler Brinks

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 Castle.MicroKernel;
Expand All @@ -10,7 +33,7 @@ namespace Snap.CastleWindsor
/// </summary>
/// <remarks>
/// Cannot use existing adapter from CommonServiceLocator.WindsorAdapter library.
/// It expects IWindsorContainer to be created with. But only IKernel is available in existing SNAP architecture.
/// It expects IWindsorContainer to be passed in. But only IKernel is available in existing SNAP architecture.
///
/// Thus, decide to build own simple adapter, which accepts IKernel and resolve types against it.
/// </remarks>
Expand Down
1 change: 1 addition & 0 deletions Snap.LinFu/LinFuAspectContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class LinFuAspectContainer : AspectContainer
public LinFuAspectContainer(ServiceContainer container)
{
Proxy = new MasterProxy();
Proxy.Container = new LinFuServiceLocatorAdapter(container);
_container = container;
_container.PostProcessors.Add(new AspectPostProcessor());
_container.AddService(Proxy);
Expand Down
66 changes: 66 additions & 0 deletions Snap.LinFu/LinFuServiceLocatorAdapter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
Snap v1.0

Copyright (c) 2010 Tyler Brinks

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 LinFu.IoC;
using LinFu.IoC.Interfaces;
using Microsoft.Practices.ServiceLocation;

namespace Snap.LinFu
{
/// <summary>
/// This is common service locator adapter for Castle.Windsor IoC container
/// </summary>
/// <remarks>
/// Common service locator adapter for LinFu is redistributed as source code.
/// See: http://code.google.com/p/linfu/downloads/list
/// </remarks>
public sealed class LinFuServiceLocatorAdapter : ServiceLocatorImplBase
{
readonly IServiceContainer _container;

public LinFuServiceLocatorAdapter(IServiceContainer container)
{
if (container == null)
throw new ArgumentNullException("container");

_container = container;
}

protected override object DoGetInstance(Type serviceType, string key)
{
return key != null
? _container.GetService(key, serviceType)
: _container.GetService(serviceType);
}

protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
{
return _container.AvailableServices
.Where(info => serviceType == info.ServiceType && (info.ArgumentTypes == null || info.ArgumentTypes.Count() == 0))
.Select(service => _container.GetService(service));
}
}
}
10 changes: 7 additions & 3 deletions Snap.LinFu/Snap.LinFu.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'NET40-Debug|AnyCPU' ">
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
Expand All @@ -29,7 +29,7 @@
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'NET40-Release|AnyCPU' ">
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\NET40-Release\</OutputPath>
Expand All @@ -39,7 +39,7 @@
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'NET35-Debug|AnyCPU'">
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
Expand Down Expand Up @@ -67,6 +67,9 @@
<Reference Include="LinFu.Core">
<HintPath>..\Libraries\LinFu.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Practices.ServiceLocation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\CommonServiceLocator.1.0\lib\NET35\Microsoft.Practices.ServiceLocation.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
Expand All @@ -83,6 +86,7 @@
<ItemGroup>
<Compile Include="AspectPostProcessor.cs" />
<Compile Include="LinFuAspectContainer.cs" />
<Compile Include="LinFuServiceLocatorAdapter.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SampleLinFuAopConfig.cs" />
</ItemGroup>
Expand Down
1 change: 1 addition & 0 deletions Snap.LinFu/packages.config
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="2.5.2" />
<package id="CommonServiceLocator" version="1.0" />
</packages>
23 changes: 23 additions & 0 deletions Snap.Ninject/NinjectServiceLocatorAdapter.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,26 @@
/*
Snap v1.0

Copyright (c) 2010 Tyler Brinks

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 Microsoft.Practices.ServiceLocation;
Expand Down
1 change: 1 addition & 0 deletions Snap.Tests/AutofacTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ public void Autofac_Supports_Resolving_All_Aspects_From_Container()
var orderedCode = container.Resolve<IOrderedCode>();
orderedCode.RunInOrder();

// both interceptors are resolved from container
CollectionAssert.AreEquivalent(
OrderedCode.Actions,
new[] { "first_kept_in_container", "second_kept_in_container" });
Expand Down
1 change: 1 addition & 0 deletions Snap.Tests/CastleWindsorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ public void CastleWindsor_Supports_Resolving_All_Aspects_From_Container()
var orderedCode = container.Resolve<IOrderedCode>();
orderedCode.RunInOrder();

// both interceptors are resolved from container
CollectionAssert.AreEquivalent(
OrderedCode.Actions,
new[] { "first_kept_in_container", "second_kept_in_container" });
Expand Down
72 changes: 72 additions & 0 deletions Snap.Tests/LinFuTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,5 +172,77 @@ public void LinFu_Should_Fail_To_Resolve_Component_Which_Is_Not_Registered_With_

Assert.Throws<ServiceNotFoundException>(() => container.GetService<IOrderedCode>());
}

[Test]
public void LinFu_Supports_Resolving_All_Aspects_From_Container()
{
var container = new ServiceContainer();

SnapConfiguration.For(new LinFuAspectContainer(container)).Configure(c =>
{
c.IncludeNamespace("SnapTests.*");
c.Bind<FirstInterceptor>().To<FirstAttribute>();
c.Bind<SecondInterceptor>().To<SecondAttribute>();
c.AllAspects().KeepInContainer();
});

// both aspects are registered in container
container.AddService(typeof(IOrderedCode), typeof(OrderedCode));
container.AddService(typeof(FirstInterceptor), new FirstInterceptor("first_kept_in_container"));
container.AddService(typeof(SecondInterceptor), new SecondInterceptor("second_kept_in_container"));

var orderedCode = container.GetService<IOrderedCode>();
orderedCode.RunInOrder();

// both aspects are resolved from container
CollectionAssert.AreEquivalent(
OrderedCode.Actions,
new[] { "first_kept_in_container", "second_kept_in_container" });
}

[Test]
public void LinFu_Supports_Resolving_Only_Selected_Aspects_From_Container()
{
var container = new ServiceContainer();

SnapConfiguration.For(new LinFuAspectContainer(container)).Configure(c =>
{
c.IncludeNamespace("SnapTests.*");
c.Bind<FirstInterceptor>().To<FirstAttribute>();
c.Bind<SecondInterceptor>().To<SecondAttribute>();
c.Aspects(typeof(FirstInterceptor)).KeepInContainer();
});

container.AddService(typeof(IOrderedCode), typeof(OrderedCode));
container.AddService(typeof(FirstInterceptor), new FirstInterceptor("first_kept_in_container"));
container.AddService(typeof(SecondInterceptor), new SecondInterceptor("second_kept_in_container"));

var orderedCode = container.GetService<IOrderedCode>();
orderedCode.RunInOrder();

// first interceptor is resolved from container, while second one is via new()
CollectionAssert.AreEquivalent(
OrderedCode.Actions,
new[] { "first_kept_in_container", "Second" });
}

[Test]
public void LinFu_Fails_When_Aspect_Is_Configured_To_Be_Resolved_From_Container_But_Was_Not_Registered_In_It()
{
var container = new ServiceContainer();

SnapConfiguration.For(new LinFuAspectContainer(container)).Configure(c =>
{
c.IncludeNamespace("SnapTests.*");
c.Bind<HandleErrorInterceptor>().To<HandleErrorAttribute>();
c.Aspects(typeof(HandleErrorInterceptor)).KeepInContainer();
});

// register only ordered code, but register neither FirstInterceptor nor SecondInteceptor in container
container.AddService(typeof(IBadCode), typeof(BadCode));

var failure = Assert.Throws<ActivationException>(container.GetService<IBadCode>().GiddyUp);
Assert.That(failure.InnerException, Is.InstanceOf<ServiceNotFoundException >());
}
}
}
22 changes: 1 addition & 21 deletions Snap.Tests/NinjectTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,27 +161,6 @@ public void Ninject_Supports_Types_Without_Interfaces()
Assert.IsTrue(typeWithInterfaceInBaseClass.GetType().Name.Equals("TypeWithInterfaceInBaseClassProxy"));
}

[Test]
public void NInject_Container_Does_Not_Support_Resolving_Aspects_From_Container()
{
var container = new NinjectAspectContainer();

SnapConfiguration.For(container).Configure(c =>
{
c.IncludeNamespace("SnapTests*");
c.Bind<HandleErrorInterceptor>().To<HandleErrorAttribute>();

// not supported now
c.AllAspects().KeepInContainer();
});

// do not register HandleErrorInterceptor in container
container.Kernel.Bind<IBadCode>().To<BadCode>();

// no failure, HandleErrorInterceptor is created via new() and intercepted
Assert.DoesNotThrow(container.Kernel.Get<IBadCode>().GiddyUp);
}

[Test]
public void Ninject_Supports_Resolving_All_Aspects_From_Container()
{
Expand All @@ -202,6 +181,7 @@ public void Ninject_Supports_Resolving_All_Aspects_From_Container()
var orderedCode = container.Kernel.Get<IOrderedCode>();
orderedCode.RunInOrder();

// both interceptors are resolved from container
CollectionAssert.AreEquivalent(
OrderedCode.Actions,
new[] { "first_kept_in_container", "second_kept_in_container" });
Expand Down