Jim Phelan
Jim Phelan

Reputation: 31

Autofac DI, type not assignable to service

I simply cannot figure this out. Using Autofac with .Net core 2.0 and trying to resolve some simple dependencies. Feel like I've tried everything so my current code doesn't reflect everything I've tried.

Here is one of the exceptions I'm getting from Autofac

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Elucidate.Core.Application.ValuesController' can be invoked with the available services and parameters: Cannot resolve parameter 'Elucidate.Core.Data.Repository.IRepository'1[Elucidate.Core.Model.User.IUser]rep' of constructor 'Void .ctor(Elucidate.Core.Data.Repository.IRepository`

Here is where I'm trying to get the dependency injected

public ValuesController(IRepository<IUser> rep)

Here is how I'm registering the types in an autofac module

builder.RegisterType<User>().As<IUser>();
builder.RegisterType<CoreUserStore<User>>();

builder.RegisterType(typeof(Repository<User>)).As<Repository<IUser>>();
builder.RegisterType<EntityFrameworkModelContext<User>>(); //.As<IModelContext>();

What am I doing wrong? I'm new to autofac, used to Unity which seems to be extinct.

Upvotes: 3

Views: 2432

Answers (1)

xenolightning
xenolightning

Reputation: 4230

The ValuesController constructor is expecting IRepository<IUser> and you haven't wired the correct type in Autofac.

You need to register the concrete repository type as the implemented interface, note the .As<IRepository...:

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

Or alternatively "ask" for the concrete type in the constructor.

public ValuesController(Repository<IUser> rep)

The first is probably the preferred approach. You can also do:

builder.RegisterType<Repository<User>>().AsImplementedInterfaces();

Which will register the concrete type as all implemented interfaces.

Upvotes: 3

Related Questions