asp.net-mvc 尝试创建类型为“TypeNewsController”的控制器时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24992712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
An error occurred when trying to create a controller of type 'TypeNewsController'
提问by Football-Is-My-Life
I have searched long and hard but found nothing that helped yet. Where am I going wrong? I really do not know what to do. I wrote all the details below. I've tried and did not succeed.
我已经搜索了很长时间,但没有发现任何帮助。我哪里错了?我真的不知道该怎么办。我在下面写了所有细节。我试过了,没有成功。
An error occurred when trying to create a controller of type 'TypeNewsController'. Make sure that the controller has a parameterless public constructor.
尝试创建类型为“TypeNewsController”的控制器时发生错误。确保控制器具有无参数的公共构造函数。
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Bootstrapper.Run();
}
}
my apicontroller :
我的 api 控制器:
public class TypeNewsController : ApiController
{
private readonly ITypeNewsService _typeNewsService;
public TypeNewsController(ITypeNewsService typeNewsService)
{
_typeNewsService = typeNewsService;
}
[HttpGet]
public TypeNewsResponse Get([ModelBinder] PageRequest model)
{
model = model ?? new PageRequest();
var output = _typeNewsService.GetTypeNewss().ToList();
return new TypeNewsResponse
{
Page = model.PageIndex,
Records = model.PageSize,
Rows = output.ToList(),
Total = output.Count() / model.PageSize,
};
}
}
error :
错误 :
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
An error occurred when trying to create a controller of type 'TypeNewsController'. Make sure that the controller has a parameterless public constructor.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType) at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()
</StackTrace>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'JuventusNewsSiteApk.Controllers.TypeNewsController' does not have a default constructor
</ExceptionMessage>
<ExceptionType>System.ArgumentException</ExceptionType>
<StackTrace>
at System.Linq.Expressions.Expression.New(Type type) at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator) at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
</StackTrace>
</InnerException>
</Error>
Bootstrapper class :
引导程序类:
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.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerRequest();
builder.RegisterAssemblyTypes(typeof(NewsRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces().InstancePerRequest();
builder.RegisterAssemblyTypes(typeof(NewsService).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces().InstancePerRequest();
builder.RegisterAssemblyTypes(typeof(DefaultFormsAuthentication).Assembly)
.Where(t => t.Name.EndsWith("Authentication"))
.AsImplementedInterfaces().InstancePerRequest();
builder.Register(
c => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new JuventusNewsApkEntities())))
.As<UserManager<ApplicationUser>>().InstancePerRequest();
builder.RegisterFilterProvider();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
update :
更新 :
public class TypeNewsService : ITypeNewsService
{
private readonly ITypeNewsRepository _typeNewsRepository;
private readonly IUnitOfWork _unitOfWork;
public TypeNewsService(ITypeNewsRepository typeNewsRepository,
IUnitOfWork unitOfWork)
{
_typeNewsRepository = typeNewsRepository;
_unitOfWork = unitOfWork;
}
#region ITypeNewsService Member
public void AddTypeNews(TypeNews typeNews)
{
_typeNewsRepository.Add(typeNews);
SaveTypeNews();
}
public void DeleteTypeNews(int id)
{
_typeNewsRepository.DeleteById(id);
SaveTypeNews();
}
public IEnumerable<TypeNews> GetTypeNewss()
{
var output = _typeNewsRepository.GetAll();
return output;
}
public void SaveTypeNews()
{
_unitOfWork.Commit();
}
#endregion
}
public interface ITypeNewsService
{
void AddTypeNews(TypeNews typeNews);
void DeleteTypeNews(int id);
IEnumerable<TypeNews> GetTypeNewss();
void SaveTypeNews();
}
回答by trailmax
Your controller is WebApicontroller and registration for Autofac differs from MVC registration. WebApi does not use DependencyResolver, so you'll need to tell WebApi to use Autofac resolver specifically.
您的控制器是WebApi控制器,Autofac 的注册与 MVC 注册不同。WebApi 不使用DependencyResolver,因此您需要告诉 WebApi 专门使用 Autofac 解析器。
You'll need to add this to your SetAutofacContainercode:
您需要将此添加到您的SetAutofacContainer代码中:
// Create the depenedency resolver.
var resolver = new AutofacWebApiDependencyResolver(container);
// Configure Web API with the dependency resolver.
GlobalConfiguration.Configuration.DependencyResolver = resolver;
See https://code.google.com/p/autofac/wiki/WebApiIntegrationfor more info.
有关更多信息,请参阅https://code.google.com/p/autofac/wiki/WebApiIntegration。
回答by VivekDev
In my case, the reason was that the resolver could not find a mapping. That is, suppose say HomeController has a dependency on IDumb, the resolver could not find a concrete implementation of Dumb which implements IDumb.
就我而言,原因是解析器找不到映射。也就是说,假设 HomeController 依赖于 IDumb,解析器找不到实现 IDumb 的 Dumb 的具体实现。
In other words the error message
换句话说,错误信息
**No parameterless constructor defined for this object
An error occurred when trying to create a controller of type 'ToDoListT1.WebApp.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor**
is completely misleading.
完全是误导。
In my case I just resolved by adding a reference to the project of the class Dumb. It should have been something like "No mapping for IDumb could be found.". I am not sure whether the problem is with NInject or MS. Whatever, it took me hours to find this out.
就我而言,我只是通过添加对 Dumb 类项目的引用来解决。它应该类似于“找不到 IDumb 的映射。”。我不确定问题是出在 NInject 还是 MS 上。无论如何,我花了好几个小时才发现这一点。
回答by David Castro
Make you sure than you're calling the same call type, I mean, Get, Post, Put, and what kind you have in the controller method.
确保您调用的是相同的调用类型,我的意思是,Get、Post、Put 以及您在控制器方法中拥有的类型。
And do you need to add your valid repository to NijectConfig.cs for the controller.
您是否需要将您的有效存储库添加到控制器的 NijectConfig.cs 中。
kernel.Bind<[iRepo]>().To<[Repo]>().InRequestScope();
kernel.Bind<[iRepo]>().To<[Repo]>().InRequestScope();
回答by Sujit Patil
For controller you should have parameter less constructor. If you want to use parametrized constructor please use code like below.
对于控制器,您应该有无参数的构造函数。如果您想使用参数化构造函数,请使用如下代码。
Pass object of TypeNewsService class
TypeNewsService 类的传递对象
private readonly ITypeNewsService _typeNewsService;
public TypeNewsController():this(new TypeNewsService ())
{
}
public TypeNewsController(ITypeNewsService typeNewsService)
{
_typeNewsService = typeNewsService;
}

