[英]Using a Repository getting error No parameterless constructor defined for this object
I am learning how to setup a repository. 我正在学习如何设置存储库。 I am going for simple and dumb just to make it work.
我想简单而愚蠢只是为了让它发挥作用。 Good thing is that may make it easy to debug for you guys.
好的是,这可能会让你们很容易调试。
HomeController: HomeController的:
public IUserRepository UserRepository { get; set; }
public HomeController(IUserRepository userRepo)
{
UserRepository = userRepo;
}
public ActionResult Index()
{
var users = UserRepository.GetUsers();
return View(users);
}
UserModel: 的usermodel:
public class UserModel
{
public int Id { get; set; }
public string UserName { get; set; }
public string PasswordHash { get; set; }
public string PasswordSalt { get; set; }
}
Repository: 库:
public interface IUserRepository
{
List<UserModel> GetUsers();
}
public class UserRepository : IUserRepository
{
private GameAlertDBDataContext db = new GameAlertDBDataContext();
public List<UserModel> GetUsers()
{
var userList = from u in db.Users where u.Id == 1 select u;
var users = new List<UserModel>();
if (userList.Any())
{
foreach (var user in userList)
{
users.Add(new UserModel() { Id = user.Id, UserName = user.Username, PasswordHash = user.PasswordHash, PasswordSalt = user.PasswordSalt});
}
}
return users;
}
}
When I run my application I get the error No parameterless constructor defined for this object. 当我运行我的应用程序时,出现错误“没有为此对象定义无参数构造函数”。
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +66
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'FriendAlert.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +179
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +193
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +49
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +49
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I am trying to figure out what I am doing wrong? 我想弄清楚我做错了什么? Why is my repository not working?
为什么我的存储库无法运行?
You have to use Dependency Injection. 您必须使用依赖注入。 I use Ninject IoC container.
我使用Ninject IoC容器。 You can install to your visual studio by Tools -> library package manager -> Manage NuGet Packages
您可以通过工具->库包管理器->管理NuGet包安装到Visual Studio。
Then add a class like this 然后添加这样的课程
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext
requestContext, Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<IUserRepository>().To<UserRepository>();
}
}
then in the Global.asax 然后在Global.asax中
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
It will solve the issue 它将解决这个问题
This error occurs because mvc framework can't find parameterless constructor in your HomeController
. 发生此错误是因为mvc框架无法在
HomeController
找到无参数构造函数。 In order to fix this issue, you just simply add a parameterless constructor so mvc framework can instantiate HomeController
为了解决此问题,您只需添加无参数构造函数,以便mvc框架可以实例化
HomeController
public HomeController()
{
}
Edit to complete my answer, as @Eranga suggested, you should consider to use Dependency Injection
framework to inject your dependency into HomeController
. 编辑以完成我的答案,正如@Eranga所建议的那样,您应该考虑使用
Dependency Injection
框架将依赖项注入到HomeController
。 You can refer to this question for more information about which framework should be used 您可以参考此问题以获取有关应使用哪个框架的更多信息。
The Asp.NET MVC framework cannot instantiate your controller because it does not have information to pass the constructor parameter. Asp.NET MVC框架无法实例化您的控制器,因为它没有传递构造函数参数的信息。
The next step here is to use Dependency Injection to construct the appropriate Repository instance and inject it to create the controller instance. 这里的下一步是使用依赖注入来构造适当的Repository实例并将其注入以创建控制器实例。
Take a look at DI framework like Autofac and how to integrate it with MVC . 看看像Autofac这样的DI框架以及如何将它与MVC集成 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.