ASP.NET 5 vNext依赖项注入(RoleManager) [英] ASP.NET 5 vNext Dependencies Injection (RoleManager)

查看:94
本文介绍了ASP.NET 5 vNext依赖项注入(RoleManager)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将UserManager之类的RoleManager传递给我的控制器,但出现此错误:

I'm trying to pass to my controller the RoleManager like UserManager, but I have this error:

处理请求时发生未处理的异常.

An unhandled exception occurred while processing the request.

InvalidOperationException:无法解析类型的服务 'Microsoft.AspNet.Identity.RoleManager`1 [Web.MongoDBIdentitySample.Models.ApplicationRole]' 尝试激活时 "Web.MongoDBIdentitySample.Controllers.AccountController".

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNet.Identity.RoleManager`1[Web.MongoDBIdentitySample.Models.ApplicationRole]' while attempting to activate 'Web.MongoDBIdentitySample.Controllers.AccountController'.

这是我的ConfigureServices方法:

This is my ConfigureServices method:

// This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Registers MongoDB conventions for ignoring default and blank fields
        // NOTE: if you have registered default conventions elsewhere, probably don't need to do this
        RegisterClassMap<ApplicationUser, IdentityRole, string>.Init();

        // Add Mongo Identity services to the services container.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddMongoDBIdentityStores<ApplicationDbContext, ApplicationUser, IdentityRole, string>(options =>
            {
                options.ConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];        // No default, must be configured if using (eg "mongodb://localhost:27017")
                // options.Client = [IMongoClient];                                 // Defaults to: uses either Client attached to [Database] (if supplied), otherwise it creates a new client using [ConnectionString]
                // options.DatabaseName = [string];                                 // Defaults to: "AspNetIdentity"
                // options.Database = [IMongoDatabase];                             // Defaults to: Creating Database using [DatabaseName] and [Client]

                // options.UserCollectionName = [string];                           // Defaults to: "AspNetUsers"
                // options.RoleCollectionName = [string];                           // Defaults to: "AspNetRoles"
                // options.UserCollection = [IMongoCollection<TUser>];              // Defaults to: Creating user collection in [Database] using [UserCollectionName] and [CollectionSettings]
                // options.RoleCollection = [IMongoCollection<TRole>];              // Defaults to: Creating user collection in [Database] using [RoleCollectionName] and [CollectionSettings]
                // options.CollectionSettings = [MongoCollectionSettings];          // Defaults to: { WriteConcern = WriteConcern.WMajority } => Used when creating default [UserCollection] and [RoleCollection]

                // options.EnsureCollectionIndexes = [bool];                        // Defaults to: false => Used to ensure the User and Role collections have been created in MongoDB and indexes assigned. Only runs on first calls to user and role collections.
                // options.CreateCollectionOptions = [CreateCollectionOptions];     // Defaults to: { AutoIndexId = true } => Used when [EnsureCollectionIndexes] is true and User or Role collections need to be created.
                // options.CreateIndexOptions = [CreateIndexOptions];               // Defaults to: { Background = true, Sparse = true } => Used when [EnsureCollectionIndexes] is true and any indexes need to be created.
            })
            .AddDefaultTokenProviders();

        services.AddIdentity<ApplicationRole, IdentityRole>()
            .AddMongoDBIdentityStores<ApplicationDbContext, ApplicationUser, IdentityRole, string>(options =>
            {
                options.ConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];        // No default, must be configured if using (eg "mongodb://localhost:27017")
                                                                                                            // options.Client = [IMongoClient];                                 // Defaults to: uses either Client attached to [Database] (if supplied), otherwise it creates a new client using [ConnectionString]
                                                                                                            // options.DatabaseName = [string];                                 // Defaults to: "AspNetIdentity"
                                                                                                            // options.Database = [IMongoDatabase];                             // Defaults to: Creating Database using [DatabaseName] and [Client]

                // options.UserCollectionName = [string];                           // Defaults to: "AspNetUsers"
                // options.RoleCollectionName = [string];                           // Defaults to: "AspNetRoles"
                // options.UserCollection = [IMongoCollection<TUser>];              // Defaults to: Creating user collection in [Database] using [UserCollectionName] and [CollectionSettings]
                // options.RoleCollection = [IMongoCollection<TRole>];              // Defaults to: Creating user collection in [Database] using [RoleCollectionName] and [CollectionSettings]
                // options.CollectionSettings = [MongoCollectionSettings];          // Defaults to: { WriteConcern = WriteConcern.WMajority } => Used when creating default [UserCollection] and [RoleCollection]

                // options.EnsureCollectionIndexes = [bool];                        // Defaults to: false => Used to ensure the User and Role collections have been created in MongoDB and indexes assigned. Only runs on first calls to user and role collections.
                // options.CreateCollectionOptions = [CreateCollectionOptions];     // Defaults to: { AutoIndexId = true } => Used when [EnsureCollectionIndexes] is true and User or Role collections need to be created.
                // options.CreateIndexOptions = [CreateIndexOptions];               // Defaults to: { Background = true, Sparse = true } => Used when [EnsureCollectionIndexes] is true and any indexes need to be created.
            })
            .AddDefaultTokenProviders();

        // Add MVC services to the services container.
        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }

这是我的AccountController类:

This is my AccountController class:

public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<ApplicationRole> _roleManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IEmailSender _emailSender;
        private readonly ISmsSender _smsSender;
        private readonly ILogger _logger;

        public AccountController(
            UserManager<ApplicationUser> userManager,
            RoleManager<ApplicationRole> roleManager,
            SignInManager<ApplicationUser> signInManager,
            IEmailSender emailSender,
            ISmsSender smsSender,
            ILoggerFactory loggerFactory)
        {
            _userManager = userManager;
            _roleManager = roleManager;
            _signInManager = signInManager;
            _emailSender = emailSender;
            _smsSender = smsSender;
            _logger = loggerFactory.CreateLogger<AccountController>();
        }
}

添加了我的ApplicationRole类:

public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDatabaseContext<ApplicationUser, ApplicationRole, string>
{
}

public class ApplicationRole : IdentityRole
{

}

任何想法如何注入?谢谢!

Any ideas how to inject this? Thanks!!

推荐答案

您在调用services.AddIdentity<ApplicationUser, IdentityRole>()时指定的是IdentityRole而不是ApplicationRole,这会注册RoleManager<IdentityRole>,但不会注册您的帐户控制者RoleManager<ApplicationRole>使用.

You're specifying IdentityRole instead of ApplicationRole when calling services.AddIdentity<ApplicationUser, IdentityRole>(), which registers RoleManager<IdentityRole> but not the RoleManager<ApplicationRole> your account controller is using.

在您的ConfigureServices方法中用ApplicationRole替换IdentityRole,它应该可以工作:

Replace IdentityRole by ApplicationRole in your ConfigureServices method and it should work:

services.AddIdentity<ApplicationUser, ApplicationRole>()
        .AddMongoDBIdentityStores<ApplicationDbContext, ApplicationUser, ApplicationRole, string>();

这篇关于ASP.NET 5 vNext依赖项注入(RoleManager)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆