JINESH
JINESH

Reputation: 1452

ASP.NET Core Identity UserManager<ApplicationUser> -Error No parameterless constructor defined for this object

I am just trying to develop a sample project for authentication and authorization, and following the link

ASP.NET Core MVC: Authentication and Role Based Authorisation with Identity

When running the code, I get an error

enter image description here

Stack Trace:

[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) +119
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +247 System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +11 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55

[InvalidOperationException: An error occurred when trying to create a controller of type 'SampleAuthProject.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.] System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +76
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +88
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +194 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

I think this error due to DI.

So in my startup.cs contains

public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
}
public Startup()
{
    var builder = new ConfigurationBuilder();
    Configurations = builder.Build();
}
public IConfigurationRoot Configurations { get; }
public void ConfigureServices(IServiceCollection services)
{
    try
    {
        services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configurations.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();
        services.AddTransient<UserManager<ApplicationUser>>();
        services.AddTransient<ApplicationDbContext>();
    }
    catch (Exception ex)
    {
        throw ex;
    }

}
public void Configure(IApplicationBuilder app,
               IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseIdentity();
}

My HomeController is

 [Microsoft.AspNetCore.Authorization.Authorize]
public class HomeController : Controller
{
    private readonly UserManager<ApplicationUser> userManager;

    public HomeController(UserManager<ApplicationUser> userManager)
    {
        this.userManager = userManager;
    }
    [Microsoft.AspNetCore.Authorization.Authorize(Roles = "User")]
    public ActionResult Index()
    {
        //userManager=new UserManager<ApplicationUser>();
        string userName =  userManager.GetUserName(System.Security.Claims.ClaimsPrincipal.Current);
        return View("Index",userName);
    }       
}

Upvotes: 1

Views: 2327

Answers (1)

Nkosi
Nkosi

Reputation: 247088

It appears you are trying to mix framework versions.

The Startup is using both IAppBuilder, which is from asp.net-mvc-5 and IApplicationBuilder, which is from the more recent asp.net-core.

Also, the exception message

No parameterless constructor defined for this object

is commonly associated with the vague messages that were returned from MVC 5 and Web.Api 2.*

This basically means that the Identity dependencies are not know to the dependency injection framework for that project, which is why it is unable to inject the dependencies into the controllers.

Either make sure that the project is in fact an asp.net-core project to be able to use asp.net-core-identity

Introduction to Identity on ASP.NET Core

Or use the correct version of Identity Framework for MVC 5.

Introduction to ASP.NET Identity

Upvotes: 1

Related Questions