Search code examples
c#.netunit-testingiofilesystems

System.IO.Abstraction: Autofac.Core.DependencyResolutionException: 'An error occurred during the activation of a particular registration


Background

I started using the NuGet package System.IO.Abstractions to unit-test File methods (File.Exists(), File.OpenRead(), File.Move(), etc.). I installed the NuGet in both the unit test project and the product code project. I did not install any of the additional related packages. My unit test works well.

In the product code

 private readonly System.IO.Abstractions.IFileSystem _fs;

 public MyClass(
     System.IO.Abstractions.IFileSystem fileSystem,
     ...
 )
 {
     _fs = fileSystem;
     ...
 }

In the unit-test code

using System.IO.Abstractions;
...

private Mock<FileSystem> mockFS;
...

public MyClassTests()
{
    mockFS = new Mock<FileSystem>();
    ...

    sut = new MyClass(
        mockFS.Object,
        ...
    );
}

Problem

Even though the unit test works, the product code throws an error:

Autofac.Core.DependencyResolutionException: 'An error occurred during the activation of a particular registration. See the inner exception for details...'

Things I've tried

  • System.IO.Abstraction's README.md doesn't mention registering its FileSystem.
  • Presumably, I need to register System.IO.Abstraction's FileSystem (or IFileSystem?) class. I've tried various iterations of
builder.RegisterType<IFileSystem>().AsImplementedInterfaces().InstancePerDependency();

but I can't seem to get it right.


Solution

  • Solution

    I eventually tried registering

    builder.RegisterType<System.IO.Abstractions.FileSystem>()
        .AsImplementedInterfaces()
        .SingleInstance();
    

    and both the product code and test code succeed!

    Note: Use the concrete FileSystem, not IFileSystem.