带有存储库和ninject的ASP.NET MVC MembershipProvider

时间:2010-10-11 17:05:33

标签: asp.net-mvc ninject membership-provider

如何通过覆盖的MembershipProvider类与UserService进行通信?我不知道如何将连接字符串传递给服务中的用户存储库。

这就是我的应用程序的结构:

Repository(实现中的构造函数采用连接字符串)

public interface IUserRepository
{
    IQueryable<User> GetUsers();
    IQueryable<UserRole> GetUserRoles();
    void InsertUser(User user);
}

服务(构造函数采用用户存储库)

public interface IUserService
{
    User GetUser(int userId);
    User GetUser(string email);
}

UserController(我的控制器的一个例子)

public class UsersController : Controller
{
    private IUserService userService;
    public UsersController(IUserService userServ)
    {
        userService = userServ;
    }
}

NinjectConfigurationModule

public class NinjectConfigurationModule : NinjectModule
{

    public override void Load()
    {
        Bind<IUserService>().To<UserService>();
        Bind<IUserRepository>().To<UserRepository>()
            .WithConstructorArgument("connectionString", ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString
            );
    }
}

NinjectControllerFactory

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel kernel = new StandardKernel(new NinjectConfigurationModule());

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        // We don't want to pass null to ninject as we'll get a strange error.
        return controllerType == null ? null
                                      : (IController)kernel.Get(controllerType);
    }
}

MembershipProvider(这是我的问题所在)

public class SimpleMembershipProvider : MembershipProvider
{
     //How do I set up User Service here so that ninject can put my connection string here.
     public override bool ValidateUser(string username, string password)
     {
           //Code to use user service.
     }
}

2 个答案:

答案 0 :(得分:19)

已经回答了问题,但我认为更好的答案是将存储库作为MembershipProvider的属性并在Application_Start中注入它。 e.g。

public class AccountMembershipProvider : MembershipProvider
{
    [Inject]
    public IAccountRepository AccountRepository { get; set; }
    ...
}

和注射:

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        // Inject account repository into our custom membership & role providers.
        _kernel.Inject(Membership.Provider);

        // Register the Object Id binder.
        ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder()); 
    }

我在这里写了一个更深入的解释:

http://www.danharman.net/2011/06/23/asp-net-mvc-3-custom-membership-provider-with-repository-injection/

答案 1 :(得分:3)

您可以覆盖MembershipProvider.Initialize函数,还需要在web.config中进行一些设置

public override void Initialize(string name, NameValueCollection config) {
    // Validate arguments
    if (config == null) throw new ArgumentNullException("config");

    // Initialize base class
    base.Initialize(name, config);

    // Initialize current class
    this.configuration = config;
    System.Configuration.ConnectionStringSettings ConnectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
    if (ConnectionStringSettings == null || ConnectionStringSettings.ConnectionString.Trim() == "") throw new ProviderException("Connection string cannot be blank.");
    // then you can create a new user service using the connection string: SimpleAuthDb
}

的web.config

<membership defaultProvider="MyMembershipProvider">
    <providers>
        <clear/>
        <add name="MyMembershipProvider"
             type="Web.SimpleSqlMembershipProvider"
             connectionStringName="SimpleAuthDb" />
    </providers>
</membership>

我还创建了一个像您一样的自定义成员资格提供程序 在用户控制器的登录操作中,将调用validateuser函数,如下所示:

Membership.ValidateUser(userName, password);

但最终我放弃了会员提供商并在 IUserService 中添加了新功能 ValidateUser ,然后是以下代码:

userService.ValidateUser(userName, password);

我认为这更简单。