misha130
misha130

Reputation: 5746

Autofac Generic interface is not assignable to service

I have like 20 registrations like these in an app:

builder.RegisterType(typeof(FilterParser<>)).As(typeof(IFilterParser<>)).InstancePerDependency();

When I try to build my container I get an error like so:

The type 'My.Namespace.FilterParser`1[TEntity]' is not assignable to service 'My.Namespace.IFilterParser`1'.'

Note the difference is the [TEntity] in the implementation and lack thereof in the interface.

My services do implement the interfaces:

public class FilterParser<TEntity> : IFilterParser<TEntity> where TEntity : new () 

public interface IFilterParser<TEntity> where TEntity : new () 

I also implemented this registration using .net core and it works just fine but in Autofac it just refuses to work.

I even tried AsImplementedInterfaces and I get the same error

builder.RegisterType(typeof(FilterParser<>)).AsImplementedInterfaces()
                        .InstancePerDependency();

Upvotes: 1

Views: 1313

Answers (1)

Nkosi
Nkosi

Reputation: 247531

Use the RegisterGeneric() builder method:

builder.RegisterGeneric(typeof(FilterParser<>))
    .As(typeof(IFilterParser<>))
    .InstancePerDependency();

When a matching service type is requested from the container, Autofac will map this to an equivalent closed version of the implementation type

Reference Registration Concepts: Open Generic Components

Upvotes: 5

Related Questions