Ninject依赖注入以提供角色和成员资格

时间:2014-06-16 11:01:20

标签: entity-framework model-view-controller dependency-injection asp.net-mvc-5

我正在尝试构建我的用户存储库(实体框架)的Dependecy Injection,并使用它来帮助在我的MVC Web应用程序中创建角色。会员提供商似乎工作正常。

的Web.config:

<membership defaultProvider="MyMembershipProvider">
  <providers>
    <clear/>  
    <add name="MyMembershipProvider" type="MyApp.Infrastructure.Concrete.CustomMembershipProvider" />
  </providers>
</membership>

<roleManager enabled="true" defaultProvider="MyRoleProvider">
  <providers>
    <clear/>
    <add name="MyRoleProvider" type="MyApp.Infrastructure.Concrete.CustomRoleProvider" />
  </providers>
</roleManager>

我的Ninject模块:

internal class MyNinjectModules : NinjectModule
{
    public override void Load()
    {
        Bind<IUserRepository>().To<EFUserRepository>();
    }
}
public class MvcApplication : System.Web.HttpApplication
{
    private IKernel ninjectKernel = new StandardKernel(new MyNinjectModules());
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        ModelBinders.Binders.Add(typeof(Cart), new CartModelBinder());

        ninjectKernel.Inject(Membership.Provider);
        ninjectKernel.Inject(Roles.Provider);
    }
}

自定义会员提供商:

public class CustomMembershipProvider : MembershipProvider
{
    private static List<User> Users = new List<User>();

    [Inject]
    public IUserRepository userRepo { get; set; }

    public override bool ValidateUser(string username, string password)
    {
        Users = userRepo.Users.ToList();
        return Users.Exists(u => u.Name == username && u.Password == password);
    }
}

自定义角色提供者:

public class CustomRoleProvider : RoleProvider
{
    private static List<User> Users = new List<User>();

    [Inject]
    public IUserRepository userRepo { get; set; }

    public override string[] GetRolesForUser(string username)
    {
        //Hardcoded roles for known users
    }
}

像这样授权:

[Authorize(Roles="SiteAdministrator")]
public class AdminController : Controller
{
    //controller
}

之前我没有使用过依赖注入,但是我必须错误地绑定我的IUserRepository?我收到这个错误:

Error activating IUserRepository
No matching bindings are available, and the type is not self-bindable.
Activation path:
   2) Injection of dependency IUserRepository into parameter userRepo of constructor of type AdminController
   1) Request for AdminController

0 个答案:

没有答案