Я пытаюсь использовать Autofac для IoC для моего проекта Asp.Net WebApi. Я пытаюсь отправить простой запрос POST в API, но безрезультатно. Я застрял на этом некоторое время и не могу понять.ASP.NET Web Api и Autofac IoC. Ошибка: ExceptionMessage = Ни один из найденных конструкторов
См. Соответствующий код и сообщите соответствующим образом. Ваша помощь будет принята с благодарностью.
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'
Большое спасибо tdragon. Это сработало. Кроме того, еще одна вещь, когда я пытаюсь отправить данные из тела запроса с помощью скрипача, в отличие от жесткого кодирования, как это было сделано выше, я получаю пустое исключение с использованием соответствующих заголовков. есть ли что-то еще, чего я не вижу здесь или каким-либо другим способом? Я приложил код ниже. заранее спасибо. Я также использую атрибут [FromBody], который не очень помог. – user6201138
Не могли бы вы отправить точный запрос, чтобы нажать от скрипача? Есть что-то [здесь] (http://stackoverflow.com/questions/11515319/frombody-not-binding-string-parameter) о публикации строкового параметра, может быть, это было бы полезно? – tdragon