c# - ASP.NET 5 vNext 依赖注入(inject) (RoleManager)

标签 c# asp.net-core

我正在尝试将 RoleManager 像 UserManager 一样传递给我的 Controller ,但出现此错误:

An unhandled exception occurred while processing the request.

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 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 类:

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
{

}

任何想法如何注入(inject)这个?谢谢!!

最佳答案

您正在指定 IdentityRole而不是 ApplicationRole打电话时 services.AddIdentity<ApplicationUser, IdentityRole>() , 注册RoleManager<IdentityRole>但不是 RoleManager<ApplicationRole>您的帐户 Controller 正在使用。

替换IdentityRole通过 ApplicationRole在你的ConfigureServices方法,它应该有效:

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

关于c# - ASP.NET 5 vNext 依赖注入(inject) (RoleManager),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34131432/

相关文章:

c# - Asp.Net Core 3.1 Appsettings 不尊重 JsonConverter

asp.net-core - Microsoft.Extensions.Logging 中是否提供强制日志记录

asp.net-core - 使用 ZXing.net 生成条形码

c# - 在 .NET MVC 中,是否有一种简单的方法来检查我是否在主页上?

c# - 在 .NET 项目中复制 native DLL 的最简洁方法

c# - ViewModel 的暴露数据取决于 View 的大小

c# - 使用终结点路由时不支持使用 'UseMvc' 配置 MVC

c# - ASP.NET Core 路由——只映射特定的 Controller

c# - 我应该如何声明我的类以反序列化以下 JSON 对象?

c# - sql——变量存储