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

时间:2016-08-12 22:58:46

标签: c# autofac

我收到以下错误消息:

  

System.InvalidOperationException:尝试时发生错误   创建一个类型的控制器   'App.Web.Controllers.ContractWizardController'。确保   controller有一个无参数的公共构造函数。 --->   Autofac.Core.DependencyResolutionException:没有构造函数   找到了   类型上的'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'   'App.Web.Controllers.ContractWizardController'可以用。调用   可用的服务和参数:无法解析参数   'App.Service.IWizardTypeStepService wizardTypeStepService'的   构造函数'Void .ctor(App.Service.IWizardTypeStepService,   App.Service.IAppBrandService,App.Service.IAppInstitutionService)'。
  在   Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext   上下文,IEnumerable 1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1   参数)在Autofac.Core.Resolving.InstanceLookup.Execute()
  在   Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope   currentOperationScope,IComponentRegistration注册,   IEnumerable 1 parameters) at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable 1个参数)at   Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration   注册,IEnumerable 1 parameters) at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable 1参数)at   Autofac.ResolutionExtensions.TryResolveService(IComponentContext   上下文,服务服务,IEnumerable 1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable 1个参数)at   Autofac.ResolutionExtensions.ResolveOptional(IComponentContext   context,类型serviceType,IEnumerable`1参数)at   Autofac.ResolutionExtensions.ResolveOptional(IComponentContext   context,输入serviceType)at   Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(类型   serviceType)at   System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(的RequestContext   requestContext,Type controllerType)---内部异常结束   堆栈跟踪--- at   System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(的RequestContext   requestContext,输入controllerType)at   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(的RequestContext   requestContext,输入controllerType)at   System.Web.Mvc.DefaultControllerFactory.CreateController(的RequestContext   requestContext,String controllerName)at   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase   httpContext,IController&控制器,IControllerFactory&厂)
  在System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase)   httpContext,AsyncCallback回调,对象状态)at   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,   AsyncCallback回调,对象状态)   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext的   context,AsyncCallback cb,Object extraData)at   System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()   在System.Web.HttpApplication.ExecuteStep(IExecutionStep步骤,   布尔和放大器; completedSynchronously)

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

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

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

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

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

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

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; }
} }

1 个答案:

答案 0 :(得分:6)

错误消息告诉您:

  

无法解析参数&#39; App.Service.IWizardTypeStepService wizardTypeStepService&#39;

您对相应服务的注册如下:

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

但是如果你看一下WizardTypeStepService,它就不会实现任何接口。实施IWizardTypeStepService,您的错误就会消失。