lundi 12 février 2018

Using Autofac in integration tests with web api 2

I have been manually instantiating my services in my integration tests, but when I got to a serve that had Lazy dependencies, I did some research and found that you can actually use Autofac to resolve your services when doing your tests.

So, I wrote this class:

public class Container<TModule> where TModule: IModule, new()
{
    private readonly IContainer _container;

    protected Container()
    {
        var builder = new ContainerBuilder();
        builder.RegisterModule(new TModule());
        _container = builder.Build();
    }

    protected TEntity Resolve<TEntity>() => _container.Resolve<TEntity>();
    protected void Dispose() => _container.Dispose();
}

And then in my context, I changed to this:

public class ProductContext : Container<AutofacModule>
{
    public IProductProvider ProductProvider { get; }
    public static ProductContext GiventServices() => new ProductContext();

    protected ProductContext()
    {
        ProductProvider = Resolve<IProductProvider>();
    }

    public List<JObject> WhenListProducts(int categoryId) => ProductProvider.List(categoryId);
}

I have another context that seems to work (the tests pass) and that is using a MatchProvider. If I compare both in my Autofac module, they look like this:

builder.RegisterType<ProductProvider>().As<IProductProvider>().InstancePerRequest();

and

builder.RegisterType<MatchProvider>().As<IMatchProvider>().SingleInstance();

Because the MatchProvider is a singelton, it seems to have no issues being resolved, but the ProductProvider is an instance per request, this is where the issue seems to lie.

I get this error when running any tests that require that service:

No scope with a tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested.

I figured it was because I didn't have the right nuget packages installed. So I installed:

  • Autofac
  • Autofac.Integration.Owin
  • Autofac.Integration.WebApi
  • Autofac.Integration.WebApi.Owin

These are the same references that are used where my module is defined, but this did not help. Does anyone know what I need to do to get this to work?

Aucun commentaire:

Enregistrer un commentaire