Unity di与web api 2身份

时间:2017-03-10 05:48:57

标签: asp.net-web-api

我已经创建了具有身份功能的AccountController,并在Web Api 2中安装了所有必需的软件包。没有Unity di工作正常但是当我尝试使用Unity DI时,它显示以下错误: 尝试创建类型为' AccountController'的控制器时发生错误。确保控制器具有无参数的公共构造函数。 StackTrace:位于System.Web.Http.Dttpcher.HttpControllerDispatcher的System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage请求)中的System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage请求,HttpControllerDescriptor controllerDescriptor,类型controllerType) .d__1.MoveNext()

我已经安装了Unity.WebAPI包

请参阅下面的代码: 的AccountController

[RoutePrefix("api/account")]
public class AccountController : ApiController
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public AccountController(IUserStore<ApplicationUser> userStore)
    {
        this._userManager = new UserManager<ApplicationUser>(userStore);
        this._roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    }

    public UserManager<ApplicationUser> UserManager         {
        get
        {
            return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
    }

    [Route("users")]
    [HttpGet]
    public IHttpActionResult GetUsers()
    {
        return Ok(this.UserManager.Users.ToList());
    }
}

UnityConfig.cs

public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        // register all your components with the container here
        // it is NOT necessary to register your controllers

        // e.g. container.RegisterType<ITestService, TestService>();
        container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
        container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
        container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());

        container.RegisterType(typeof(IRepository<>), typeof(Repository<>));
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }
}

我在Startup.Auth.cs文件中注册了UnityConfig

ApplicationDbContext.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
       : base("AspNetIdentityString", throwIfV1Schema: false)
    {
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    //public static string CongigConstants { get; private set; }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    /// <summary>
    /// The on model creating.
    /// </summary>
    /// <param name="modelBuilder">The model builder.</param>
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

ApplicationUserManager类

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var appDbContext = context.Get<ApplicationDbContext>();
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(appDbContext));

        return manager;
    }
}

Startup.Auth.cs

[assembly: OwinStartup(typeof(AspNetIdentity.API.Startup))]
namespace AspNetIdentity.API
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            HttpConfiguration httpConfig = new HttpConfiguration();
            //ConfigureOAuthTokenGeneration(app);
            UnityConfig.RegisterComponents();
           // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            ConfigureWebApi(httpConfig);

            //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            app.UseWebApi(httpConfig);

        }
        private void ConfigureWebApi(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
        }

Startup.cs

[assembly: OwinStartupAttribute(typeof(AspNetIdentity.API.Startup))]
namespace AspNetIdentity.API
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

我经常搜索但无法找到合适的解决方案。 如有任何疑虑,请通知我。

提前致谢

0 个答案:

没有答案
相关问题