简体   繁体   English

使用'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'找到的构造函数都没有

[英]None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'

I get the following error message: 我收到以下错误消息:

System.InvalidOperationException: An error occurred when trying to create a controller of type 'App.Web.Controllers.ContractWizardController'. System.InvalidOperationException:尝试创建“App.Web.Controllers.ContractWizardController”类型的控制器时发生错误。 Make sure that the controller has a parameterless public constructor. 确保控制器具有无参数的公共构造函数。 ---> Autofac.Core.DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'App.Web.Controllers.ContractWizardController' can be invoked with the available services and parameters: Cannot resolve parameter 'App.Service.IWizardTypeStepService wizardTypeStepService' of constructor 'Void .ctor(App.Service.IWizardTypeStepService, App.Service.IAppBrandService, App.Service.IAppInstitutionService)'. ---> Autofac.Core.DependencyResolutionException:可以使用可用的服务和参数调用在'App.Web.Controllers.ContractWizardController'类型上找到'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'的构造函数:无法解析构造函数'Void .ctor(App.Service.IWizardTypeStepService,App.Service.IAppBrandService,App.Service.IAppInstitutionService)'的参数'App.Service.IWizardTypeStepService wizardTypeStepService'。
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable 1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1 parameters) at Autofac.Core.Resolving.InstanceLookup.Execute() 在Autofac.Core.Core.Resolving.InstanceLookup.Execute( 1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1参数)中的Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext上下文,IEnumerable 1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable 1 parameters) at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable 1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable 1 parameters) at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable 1 parameters) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable 1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable 1 parameters) at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope,IComponentRegistration注册,IEnumerable 1 parameters) at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable IComponentRegistration注册,IEnumerable的1 parameters) at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable 1个参数)在Autofac.ResolutionExtensions.TryResolveService(IComponentContext上下文中,服务服务,IEnumerable的1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable Autofac.ResolutionExtensions.ResolveOptional(IComponentContext上下文,类型serviceType,IEnumerable`1参数)中的1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable 1参数),位于Autofac.ResolutionExtensions.ResolveOptional(IComponentContext上下文,类型serviceType) ) at Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType) at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) --- End of inner exception stack trace --- at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) )在System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext,Type controllerType)的Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType)---内部异常堆栈跟踪结束---在System.Web .Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(的RequestContext的RequestContext,类型controllerType)在System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(的RequestContext的RequestContext,类型controllerType)在System.Web.Mvc.DefaultControllerFactory.CreateController(的RequestContext的RequestContext,字符串controllerName)在System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext,IController&controller,IControllerFactory&factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) 在System.Web.Mvc.MvcHandler.BeginProcessRequest在System.Web.Mvc.MvcHandler.BeginProcessRequest在System.Web.Mvc.MvcHandler.System(HttpContext的HttpContext的,AsyncCallback的回调,对象状态)(HttpContextBase HttpContext的,AsyncCallback的回调,对象状态) System.Web.HttpApplication.ExecuteStep上的System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()中的.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext上下文,AsyncCallback cb,Object extraData)(IExecutionStep step,Boolean&completedSynchronously) )

Global.asax Global.asax中

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Autofac and Automapper configurations
            Bootstrapper.Run();
        }
    }

Bootstrapper.cs Bootstrapper.cs

namespace App.Web.App_Start
{
    public static class Bootstrapper
    {
        public static void Run()
        {
            SetAutofacContainer();
            //Configure AutoMapper
            AutoMapperConfiguration.Configure();
        }

        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
            builder.RegisterType<DbFactory>().As<IDbFactory>().InstancePerRequest();

            // Repositories
            builder.RegisterAssemblyTypes(typeof(AppBrandRepository).Assembly)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces()
                .InstancePerRequest();

            // Services
            builder.RegisterAssemblyTypes(typeof(AppBrandService).Assembly)
               .Where(t => t.Name.EndsWith("Service"))
               .AsImplementedInterfaces()
               .InstancePerRequest();


            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}

IRepository IRepository

namespace App.Data.Infrastructure
{
    public interface IRepository<T> where T : class
    {
        // Marks an entity as new
        void Add(T entity);
        // Marks an entity as modified
        void Update(T entity);
        // Marks an entity to be removed
        void Delete(T entity);
        void Delete(Expression<Func<T, bool>> where);
        // Get an entity by int id
        T GetById(int id);
        // Get an entity using delegate
        T Get(Expression<Func<T, bool>> where);
        // Gets all entities of type T
        IEnumerable<T> GetAll();
        // Gets entities using delegate
        IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
    }
}

RepositoryBase RepositoryBase

namespace App.Data.Infrastructure
{
    public abstract class RepositoryBase<T> where T : class
    {
        #region Properties
        private ApplicationDbContext dataContext;
        private readonly IDbSet<T> dbSet;

        protected IDbFactory DbFactory
        {
            get;
            private set;
        }

        protected ApplicationDbContext DbContext
        {
            get { return dataContext ?? (dataContext = DbFactory.Init()); }
        }
        #endregion

        protected RepositoryBase(IDbFactory dbFactory)
        {
            DbFactory = dbFactory;
            dbSet = DbContext.Set<T>();
        }

        #region Implementation
        public virtual void Add(T entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Update(T entity)
        {
            dbSet.Attach(entity);
            dataContext.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Delete(T entity)
        {
            dbSet.Remove(entity);
        }

        public virtual void Delete(Expression<Func<T, bool>> where)
        {
            IEnumerable<T> objects = dbSet.Where<T>(where).AsEnumerable();
            foreach (T obj in objects)
                dbSet.Remove(obj);
        }

        public virtual T GetById(int id)
        {
            return dbSet.Find(id);
        }

        public virtual IEnumerable<T> GetAll()
        {
            return dbSet.ToList();
        }

        public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
        {
            return dbSet.Where(where).ToList();
        }

        public T Get(Expression<Func<T, bool>> where)
        {
            return dbSet.Where(where).FirstOrDefault<T>();
        }

        #endregion

    }
}

WizardTypeStepRepository WizardTypeStepRepository

namespace App.Data.Repositories
{
    public class WizardTypeStepRepository : RepositoryBase<WizardTypeStep>, IWizardTypeStepRepository
    {
        public WizardTypeStepRepository(IDbFactory dbFactory) : base(dbFactory)
        {
        }

        public IEnumerable<StepNav> StepNav(string langCode = "en", int wizardType = 1)
        {
            using (ApplicationDbContext db = new ApplicationDbContext()) 
            {
                var step = from a in db.Steps
                           join b in db.ItemLanguages
                           on a.ItemCode equals b.ItemCode
                           where b.LangCode == langCode
                           where a.WizardTypeId == wizardType
                           select new StepNav
                           {
                               StepNo = a.StepNo,
                               ItemLegend = b.ItemLegend,
                               Url = a.Url
                           };
                return step;
            }
        }
    }

    public interface IWizardTypeStepRepository : IRepository<WizardTypeStep>
    {
        IEnumerable<StepNav> StepNav(string langCode = "en", int wizardType = 1);
    }
}

WizardTypeStepService WizardTypeStepService

namespace App.Service
{
    public interface IWizardTypeStepService
    {
        IEnumerable<WizardTypeStep> GetSteps(int Id);
        IEnumerable<StepNav> AllSteps(string language = "en", int type = 1);
    }
    public class WizardTypeStepService
    {
        private readonly IWizardTypeStepRepository wizardTypeStepRepository;
        private readonly IUnitOfWork unitOfWork;
        public WizardTypeStepService(IWizardTypeStepRepository wizardTypeStepRepository, IUnitOfWork unitOfWork)
        {
            this.wizardTypeStepRepository = wizardTypeStepRepository;
            this.unitOfWork = unitOfWork;
        }

        public IEnumerable<WizardTypeStep> GetSteps(int Id)
        {
            return wizardTypeStepRepository.GetMany(a => a.WizardTypeId == Id).OrderBy(a => a.StepNo);
        }


        public IEnumerable<StepNav> StepNav(string language = "en", int type = 1)
        {
            return wizardTypeStepRepository.StepNav(language, type);
        }
    }
}

ContractWizardController ContractWizardController

namespace App.Web.Controllers {
    public class ContractWizardController : AppController
    {
        private readonly IWizardTypeStepService wizardTypeStepService;
        public ContractWizardController(IWizardTypeStepService wizardTypeStepService, IAppBrandService brand, IAppInstitutionService institution) : base(brand, institution)
        {
            this.wizardTypeStepService = wizardTypeStepService;

            IEnumerable<StepNav> steps = wizardTypeStepService.AllSteps();
            this.Steps = new StepNavViewModel(steps)
            {
                Steps = steps
            };
            this.ViewData["Steps"] = this.Steps;
        }
    // GET: ContractWizard
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Step(int Id = 1)
    {
        ViewBag.Step = Id;
        switch (Id)
        {
            case 1:
                ViewBag.Title = "State";
                ViewBag.Message = "State content goes here...";
                break;
            case 2:
                ViewBag.Title = "Property";
                ViewBag.Message = "Property Content goes here...";
                break;
            case 3:
                ViewBag.Title = "Listing Agent";
                ViewBag.Message = "Listing Agent content goes here...";
                break;
            case 4:
                ViewBag.Title = "Selling Agent";
                ViewBag.Message = "Selling Ageng content goes here...";
                break;
            case 5:
                ViewBag.Title = "Finish";
                ViewBag.Message = "Finish content goes here...";
                break;
        }
        return View();
    }

    public StepNavViewModel Steps { get; set; }
} }

The error message tells you that : 错误消息告诉您:

Cannot resolve parameter 'App.Service.IWizardTypeStepService wizardTypeStepService' 无法解析参数'App.Service.IWizardTypeStepService wizardTypeStepService'

Your registration of the corresponding service is like this : 您对相应服务的注册如下:

// Services
builder.RegisterAssemblyTypes(typeof(AppBrandService).Assembly)
   .Where(t => t.Name.EndsWith("Service"))
   .AsImplementedInterfaces()
   .InstancePerRequest();

But if you look at WizardTypeStepService , it doesn't implement any interfaces. 但是如果你看一下WizardTypeStepService ,它就不会实现任何接口。 Implement IWizardTypeStepService and your error should disappear. 实现IWizardTypeStepService ,您的错误应该消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Autofac没有使用&#39;Autofac.Core.Activators.Reflection.DefaultConstructorFinder&#39;找到的构造函数 - Autofac None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' MVC&#39;Autofac.Core.Activators.Reflection.DefaultConstructorFinder&#39;中找不到任何构造函数 - MVC None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' 没有在类型上使用&#39;Autofac.Core.Activators.Reflection.DefaultConstructorFinder&#39;找到的构造函数 - None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 没有找到带有“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”的构造函数 - None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' 使用 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder 找不到构造函数 - None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder DependencyResolutionException:没有找到类型为“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”的构造函数 - DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type nopCommerce 项目中的 Autofac 异常(Autofac.Core.Activators.Reflection.NoConstructorsFoundException: 'No accessible constructors were found ) - Autofac exception in nopCommerce project (Autofac.Core.Activators.Reflection.NoConstructorsFoundException: 'No accessible constructors were found ) 在 Asp.NET Core 3.1 上注入依赖项时出现 Autofac.Core.Activators.Reflection.NoConstructorsFoundException - Autofac.Core.Activators.Reflection.NoConstructorsFoundException while injecting dependencies on Asp.NET Core 3.1 Autofac - 自动注册错误:没有&#39;公共绑定标志&#39;可以找到构造函数 - Autofac - auto registration error : No constructors can be found with 'Public binding flags' 对建设者的反思 - Reflection for Constructors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM