Asp.net web api ASP.NET Web Api和Autofac IoC。错误:ExceptionMessage=未找到任何构造函数

Asp.net web api ASP.NET Web Api和Autofac IoC。错误:ExceptionMessage=未找到任何构造函数,asp.net-web-api,asp.net-web-api2,autofac,Asp.net Web Api,Asp.net Web Api2,Autofac,我正在尝试在我的Asp.NETWebAPI项目中使用Autofac for IoC。我试图向API发送一个简单的POST请求,但没有效果。我在这个问题上已经纠结了一段时间,弄不明白 请参阅相关代码并提出相应建议。非常感谢你的帮助 public interface IEntityRepository<T> where T : class, new() { IQueryable<T> All { get; } IQueryable<T> AllIn

我正在尝试在我的Asp.NETWebAPI项目中使用Autofac for IoC。我试图向API发送一个简单的POST请求,但没有效果。我在这个问题上已经纠结了一段时间,弄不明白

请参阅相关代码并提出相应建议。非常感谢你的帮助

public interface IEntityRepository<T> where T : class, new()
{
    IQueryable<T> All { get; }
    IQueryable<T> AllIncluding(params Expression<Func<T,object>>[] includeProperties);
    IQueryable<T> GetAll();
    //IQueryable<T> GetSingle(string entitiesID);
    IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
    void Add(T entity);
    void Delete(T entity);
    void Edit(T entity);
    void Save();

    PaginatedList<T> Paginate<TKey>(int pageindex, int pagesize, Expression<Func<T, TKey>> keySelector);

    PaginatedList<T> Paginate<TKey>(
        int pageindex, int pagesize, 
        Expression<Func<T, TKey>> keySelector, 
        Expression<Func<T, bool>> predicate, 
        params Expression<Func<T, object>>[] includeProperties);
}

public class EntityRepository<T> : IEntityRepository<T> where T : class, new()
{
    readonly CirclesDBEntities _entitiesContext;

    public EntityRepository(CirclesDBEntities entitiesContext)
    {
        if (entitiesContext ==  null)
        {
            throw new ArgumentNullException("entitiesContext");
        }
        _entitiesContext = entitiesContext;
    }

    public virtual IQueryable<T> GetAll()
    {
        return _entitiesContext.Set<T>();
    }

    public IQueryable<T> All
    {
        get { return GetAll(); }
    }

    public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = _entitiesContext.Set<T>();
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }

    public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
    {
        return _entitiesContext.Set<T>().Where(predicate);
    }

    public virtual PaginatedList<T> Paginate<TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> keySelector)
    {
        return Paginate(pageIndex, pageSize, keySelector, null);
    }
    public virtual PaginatedList<T> Paginate<TKey>(
        int pageIndex, int pageSize, 
        Expression<Func<T, TKey>> keySelector, 
        Expression<Func<T, bool>> predicate, 
        params Expression<Func<T, object>>[] includeProperties)
    {
        IQueryable<T> query = AllIncluding(includeProperties).OrderBy(keySelector);
        query = (predicate == null) ? query : query.Where(predicate);

        return query.ToPaginatedList(pageIndex, pageSize);
    }

    public virtual void Add(T entity)
    {
        DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
        _entitiesContext.Set<T>().Add(entity);
    }

    public virtual void Edit(T entity)
    {
        DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
        dbEntityEntry.State = EntityState.Modified;
    }

    public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
        dbEntityEntry.State = EntityState.Deleted;
    }

    public virtual void Save()
    {
        _entitiesContext.SaveChanges();
    }
}

public static class TermRepository
{
    public static Term GetCurrentTerm(this IEntityRepository<Term> termRepository)
    {
        return termRepository.GetAll().OrderByDescending(x => x.DateUploaded).FirstOrDefault(); //descending puts the most recent item on top of the stack
    }
}

public class TermsService : ITermsService
{
    private readonly IEntityRepository<Term> _termRepository;

    public TermsService(IEntityRepository<Term> termRepository)
    {
        _termRepository = termRepository;
    }

    public Term GetMostRecentTerm()
    {
        Term term = _termRepository.GetCurrentTerm();
        return term;
    }

    public bool UploadNewTerm(string newTerm)
    {
        Term term = new Term();
        term.TermID = SetAccountID();
        term.Term1 = newTerm;
        term.DateUploaded = DateTime.Now;

        _termRepository.Add(term);
        _termRepository.Save();

        return true;
    }

}

public interface ITermsService
{
    Term GetMostRecentTerm();
    bool UploadNewTerm(string Term);
}

public static class AutofacConfig
{
    public static void Initialize(HttpConfiguration config)
    {
        Initialize(config,
        RegisterServices(new ContainerBuilder()));
    }
    public static void Initialize(HttpConfiguration config, IContainer container)
    {
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    }
    private static IContainer RegisterServices(ContainerBuilder builder)
    {
        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());


        // registration goes here


        //EF DbContext
        builder.RegisterType<CirclesDBEntities>()
            .As<DbContext>()
            .InstancePerRequest();

        //Repositories                        
        builder.RegisterGeneric(typeof(EntityRepository<>))
            .As(typeof(IEntityRepository<>))
            .InstancePerDependency();

        //this makes it check non-public classes
        //builder.RegisterGeneric(typeof(EntityRepository<>))
            //.As(typeof(IEntityRepository<>))
            //.InstancePerRequest().FindConstructorsWith(
               //new DefaultConstructorFinder(type =>
                  //type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)))
            //.As(typeof(IEntityRepository<>));


        //Services
        builder.RegisterType<TermsService>()
            .As<ITermsService>()
            .InstancePerRequest();


        return builder.Build();
    }
}

 public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        //Registering routes from the WebApi.Config file
        GlobalConfiguration.Configure(Config.WebApiConfig.Register);

        //Registering routes from the HelpPageAreaRegistration in the areas section
        GlobalConfiguration.Configure(CirclesWebApi.Areas.HelpPage.HelpPageAreaRegistration.RegisterAllAreas);


        GlobalConfiguration.Configure(Config.AutofacConfig.Initialize);


    }
}

public class TermsController : ApiController
{
    public readonly ITermsService _termService;

    public TermsController(ITermsService termService)
    {
        _termService = termService;
    }

    [HttpPost]
    public HttpResponseMessage PostTerms()
    {
        string terms = "terms this is a new term inserted through fiddler";

        if(terms != null)
        {
            bool created = _termService.UploadNewTerm(terms);

            if (created)
            {
                var response = Request.CreateResponse(HttpStatusCode.Created);
                return response;
            }
            else
                return Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }
}

EntityRepository
的构造函数中注入
CirclesDBEntities
,但将其注册为
DbContext
。因此,您可以通过向构造函数注入
DbContext
来解决此问题,通过删除注册的
.As()
部分或向注册中添加
.AsSelf()
来更改注册。

EntityRepository
的构造函数中注入
CirclesDBEntities
,但您将其注册为
DbContext
。因此,您可以通过向构造函数注入
DbContext
来解决此问题,通过删除注册的
.As()
部分或向注册中添加
.AsSelf()
来更改注册。

非常感谢。成功了。另外,还有一件事,当我尝试使用fiddler从请求体发送数据时,与我前面所做的硬编码不同,我使用适当的头得到一个emptyornull异常。我在这里还遗漏了什么吗?或者还有其他方法吗?我已经附上下面的代码。提前谢谢。我也在使用[FromBody]属性,这没有多大帮助。你能发布fiddler推送的确切请求吗?有一些关于发布字符串参数的信息,也许会有帮助?非常感谢。成功了。另外,还有一件事,当我尝试使用fiddler从请求体发送数据时,与我前面所做的硬编码不同,我使用适当的头得到一个emptyornull异常。我在这里还遗漏了什么吗?或者还有其他方法吗?我已经附上下面的代码。提前谢谢。我也在使用[FromBody]属性,这没有多大帮助。你能发布fiddler推送的确切请求吗?有一些关于发布字符串参数的信息,也许会有帮助?
ExceptionMessage=None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'