ASP.NET 5 vNext依赖注入(角色管理器)

5

我试图像UserManager一样将RoleManager传递给我的控制器,但是我遇到了这个错误:

在处理请求时发生未处理的异常。

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

这是我的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
{

}

有什么想法可以注入这个?谢谢!!
1个回答

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

请在您的ConfigureServices方法中将IdentityRole替换为ApplicationRole,然后它应该可以工作了。

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

在数据库上下文中将IdentityRole更改为ApplicationRole解决了我的问题,使用您的代码也很好;)谢谢 - chemitaxis
我认为我一直在使用IdentityRole,但是出现了相同的错误!我留下了问题: http://stackoverflow.com/q/40384830/1019042 - user1019042

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接