Autofac找不到带有';Autofac.果心激活剂.反射DefaultConstructorFinder

本文关键字:Autofac 激活 反射 DefaultConstructorFinder 找不到 | 更新日期: 2023-09-27 18:02:46

找不到具有"Autofac"的构造函数。果心激活剂。反射类型LMS上的DefaultConstructorFinder。服务。安全EncryptionService"可以使用可用的服务和参数调用:无法解析参数"LMS"。模型。构造函数"Void.ctor(LMS.Models.SecuritySettings("的SecuritySettings SecuritySettings

以下是的代码文件

服务类别

public class EncryptionService : IEncryptionService
{
    private readonly SecuritySettings _securitySettings;
    public EncryptionService(SecuritySettings securitySettings)
    {
        this._securitySettings = securitySettings;
    }
}

引导程序

private static void SetAutofacContainer()
{
    var builder = new ContainerBuilder();
    builder.RegisterControllers(Assembly.GetExecutingAssembly());
    builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
    builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerRequest();
    builder.RegisterAssemblyTypes(typeof(CourseRepository).Assembly)
           .Where(t => t.Name.EndsWith("Repository"))
           .AsImplementedInterfaces()
           .InstancePerRequest();
    builder.RegisterAssemblyTypes(typeof(CourseService).Assembly)
           .Where(t => t.Name.EndsWith("Service"))
           .AsImplementedInterfaces()
           .InstancePerRequest();
    builder.RegisterFilterProvider();
    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}

它工作得更早。但当我介绍EncryptionService实现时,我收到了上面的错误。以下是的其他工作代码实现

public class CourseService : ICourseService
{
    #region Fields
    private readonly IRepository<Course> _courseRepository;
    private readonly IUnitOfWork _unitOfWork;
    #endregion
    #region ctor
    public CourseService(IRepository<Course> courseRepository, IUnitOfWork unitOfWork)
    {
        _courseRepository = courseRepository;
        _unitOfWork = unitOfWork;
    }
    #endregion
}

Autofac找不到带有';Autofac.果心激活剂.反射DefaultConstructorFinder

Autofac尝试解析EncryptionService时,它会尝试解析SecuritySettings服务,但Automatc不知道此类注册。

要解决此错误,您应该注册一个SecuritySettings实现。

例如:

builder.RegisterType<SecuritySettings>()
       .As<SecuritySettings>(); 

在我的情况下,我还没有注册上下文。我注册了上下文,它对我有效

builder.RegisterType<JComDbEntities>().AsSelf().As<DbContext>().InstancePerLifetimeScope();

您还可以通过添加AnyConcreteTypeNotAlreadyRegisteredSource(请参阅来源文档(来调整Autofac的行为,使其如您最初预期的那样工作[并与其他一些容器的默认值保持一致]:-

var builder = new ContainerBuilder();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());

我将此方案与委托工厂和隐式关系类型一起使用,几乎可以从一套应用程序中删除显式注册,但由于您似乎已经走上了显式(样板:p(注册的道路,我建议在谷歌上搜索AnyConcreteTypeNotAlreadyRegisteredSource,看看更广泛的方案是否更适合您的需求。