Search code examples
c#inversion-of-controlautofacstructuremap

Registering an open-generic type in Autofac


For various reasons we are needing to use Autofac in on of our libraries. We are currently using Structuremap and are having trouble converting the following to Autofac

For(typeof(Data.New.IRepository<>)).Use(typeof(Data.New.Repository<>));

We are trying the following in Autofac

builder.RegisterType(typeof(Repository<>)).As(typeof(IRepository<>));

And receiving the following error

System.ArgumentException: 'The type 'Repository1[T]' is not assignable to service 'IRepository1'.'


Solution

  • There is a special method RegisterGeneric in Autofac for open generics:

    builder.RegisterGeneric(typeof(Repository<>))
           .As(typeof(IRepository<>))
           .InstancePerLifetimeScope();