【问题标题】:ASP.NET Web Api and Autofac IoC. Error: ExceptionMessage=None of the constructors foundASP.NET Web Api 和 Autofac IoC。错误:ExceptionMessage=未找到任何构造函数
【发布时间】:2016-08-05 06:20:45
【问题描述】:

我正在尝试将 Autofac for IoC 用于我的 Asp.Net WebApi 项目。我正在尝试向 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);
        }
    }
}

错误:

ExceptionMessage=None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'

【问题讨论】:

    标签: asp.net-web-api asp.net-web-api2 autofac


    【解决方案1】:

    EntityRepository&lt;T&gt; 的构造函数中,你注入了CirclesDBEntities,但你将它注册为DbContext。因此,您可以通过将DbContext 注入构造函数来解决此问题,通过删除.As&lt;DbContext&gt;() 部分注册或将.AsSelf() 添加到您的注册来更改您的注册。

    【讨论】:

    • 非常感谢 tdragon。那行得通。此外,还有一件事,当我尝试使用提琴手从请求正文发送数据时,而不是像我上面所做的那样对其进行硬编码,我使用适当的标头得到一个空或空异常。我在这里还有什么遗漏或任何其他方法可以解决这个问题吗?我附上了下面的代码。提前致谢。我也在使用 [FromBody] 属性,但没有太大帮助。
    • 您能否发布确切的请求以从提琴手推送? here 有关于发布字符串参数的东西,也许会有所帮助?
    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    相关资源
    最近更新 更多