我试图在我的控制台应用中使用autofac进行依赖注入。我遇到了autofac无法找到某些接口/类的构造函数的问题。
这是我最新的例子:
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;
}
}
调度程序:
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
}
}
}
类型&#39; IPlanetaryRepository&#39;上没有构造函数可以找到 构造函数查找器 &#39; Autofac.Core.Activators.Reflection.DefaultConstructorFinder&#39;
如果我拿出IPlanetaryRepository,我会得到这个例外:
无法解析构造函数的参数IPlanetaryRepository repo ...
所以我不确定该怎么做。 &#39; PlanetaryService&#39;需要&#39; IPlanetaryRepository&#39;作为参数,但IPlanetaryRepository没有构造函数。
有没有办法纠正这个问题?
答案 0 :(得分:1)
您没有任何实现IPlanetaryRepository的类,因此无法找到构造函数。