Search code examples
namespacesassembly-resolutiondynamic-proxynsubstitute

How to fix "type exists in both assemblies" failure when using DynamicProxy types in an assembly referencing NSubstitute?


I have an application that uses DynamicProxy 3.1 to do runtime interception. I have a test assembly that uses NSubstitute for mocking. I just wrote some "integration" tests against my fully bootstrapped container (StructureMap using InterceptWith to do the interception) so that I can assert that certain types coming out of the container are proxied properly.

[Subject(typeof(RobotBoard))]
public class When_resolving_an_intercepted_type : WithContainer<IRobotBoard>
{
    It should_have_recovery = () => Subject.ShouldHaveInterceptor<RecoveryInterceptor>();
}

public static class TestExtensions
{
    public static void ShouldHaveInterceptor<T>(this object obj)
        where T : IInterceptor
    {
        ((IProxyTargetAccessor)obj)
            .GetInterceptors()
            .ToList()
            .Exists(x => x is T)
            .ShouldBeTrue();
    }
}

However, I get this error, indicating that DynamicProxy references are inside the NSubstitute assembly, too! (it appears to be ilmerged).

Error    11    MyCompany.MyModule.Specifications    D:\code\source\tests\When_resolving_an_intercepted_type.cs
The type 'Castle.DynamicProxy.IProxyTargetAccessor' exists in both 'd:\code\packages\Castle.Core.3.1.0\lib\net40-client\Castle.Core.dll' and 'd:\code\packages\NSubstitute.1.4.2.0\lib\NET40\NSubstitute.dll'

Is there anyway around this conflict?


Solution

  • You could grab the NSubstitute source code and remove the ilmerge commands from the project's targets. I've opened issue 86 on their repository to address this.

    <exec command="&quot;$(MSBuildProjectDirectory)\..\..\ThirdParty\Ilmerge\ILMerge.exe&quot; /internalize:&quot;$(MSBuildProjectDirectory)\ilmerge.exclude&quot; /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly)  &quot;@(IntermediateAssembly)&quot; @(AssembliesToMerge->'&quot;%(FullPath)&quot;', ' ')" Condition=" '$(TargetFrameworkVersion)' == 'v3.5'" />
    <exec command="&quot;$(MSBuildProjectDirectory)\..\..\ThirdParty\Ilmerge\ILMerge.exe&quot; /internalize:&quot;$(MSBuildProjectDirectory)\ilmerge.exclude&quot; /keyfile:$(AssemblyOriginatorKeyFile) /out:@(MainAssembly) /targetplatform:&quot;v4,$(FrameworkReferenceAssemblyPath).&quot; &quot;@(IntermediateAssembly)&quot; @(AssembliesToMerge->'&quot;%(FullPath)&quot;', ' ')" Condition=" '$(TargetFrameworkVersion)' == 'v4.0'" />