SkyeBoniwell
SkyeBoniwell

Reputation: 7112

Registration confusion with autofac and console app

I'm trying to use autofac for dependency injection in my console app. I'm running into issues where autofac can't find constructors for certain interfaces/classes.

Here is my latest example:

IRepository:

public interface IRepository<Planetary>
{
    IEnumerable<Planetary> Get();
}

IPlanetaryRepository:

public interface IPlanetaryRepository : IRepository<Planetary>
{
    IQueryable<Planetary> GetPlanetary(SystemProbe user);
}

PlanetaryService:

public interface IPlanetaryService
{
    Task<Planetary> Clone(Planetary source);
}

public sealed class PlanetaryService : IPlanetaryService
{
    private IPlanetaryRepository Repo { get; }

    public PlanetaryService(IPlanetaryRepository repo)
    {
        Repo = repo;
    }
}

Scheduler:

public class Scheduler
{
    private static IContainer Container { get; set; }

    static void Main()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<PlanetaryService>().As<PlanetaryService>();
        builder.RegisterType<IPlanetaryRepository>().As<IPlanetaryRepository>();

        Container = builder.Build();

        GenerateSchedules();
    }

    public static void GenerateSchedules()
    {
        using (var scope = Container.BeginLifetimeScope())
        {

            var repo = scope.Resolve<PlanetaryService>();    <-- line where exception is thrown
        }
    }
}

No constructors on type 'IPlanetaryRepository' can be found with the constructor finder 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'.

If I take out IPlanetaryRepository, I get this exception:

Cannot resolve parameter IPlanetaryRepository repo of constructor...

So I'm not really sure what to do. 'PlanetaryService' needs 'IPlanetaryRepository' as a parameter, but IPlanetaryRepository doesn't have a constructor.

Is there a way to rectify this?

Upvotes: 0

Views: 675

Answers (1)

user1156000
user1156000

Reputation: 96

You don'y have any classes that implement IPlanetaryRepository so it can't find the constructor.

Upvotes: 1

Related Questions