2016-04-13 27 views
1

Asp.Net WebApi projem için IoC için Autofac kullanmaya çalışıyorum. API'ye basit bir POST isteği göndermeye çalışıyorum, ancak boşuna. Bir süredir bunun üzerinde sıkışıp kaldım ve anlayamıyorum.ASP.NET Web API ve Autofac IoC. Hata: ExceptionMessage = Kurucuların hiçbiri bulunamadı

Lütfen ilgili kodu inceleyin ve uygun şekilde önerin. Yardımınız çok takdir edilecektir.

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

Hata: EntityRepository<T> yapıcısı sen CirclesDBEntities enjekte ama DbContext olarak kayıt olarak

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

cevap

0

. Böylece, kurucunuza .As<DbContext>() kaydını kaldırarak veya .AsSelf() kaydını ekleyerek kaydınızı değiştirerek kurye DbContext enjekte ederek bunu düzeltebilirsiniz.

+0

Çok teşekkürler tdragon. İşe yaradı. Ayrıca, bir şey daha, fiddler'ı kullanarak istek gövdesinden veri göndermeye çalıştığımda, yukarıda yaptığım gibi kodlama yapmak yerine, uygun üstbilgileri kullanarak boş bir istisna elde ediyorum. Burada başka bir şey mi var, yoksa bu konuda başka bir yol var mı? Aşağıdaki kodu ekledim. şimdiden teşekkürler. Çok fazla yardımı olmayan [FromBody] özniteliğini kullanıyorum. – user6201138

+0

Fidyciden zorlamak için tam istek gönderebilir misiniz? String parametresi hakkında [burada] (http://stackoverflow.com/questions/11515319/frombody-not-binding-string-parameter) bir şey var, belki yararlı olur mu? – tdragon