asp.net-mvc – 带有存储库和ninject的ASP.NET MVC MembershipProvider

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 带有存储库和ninject的ASP.NET MVC MembershipProvider前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何通过覆盖的MembershipProvider类与UserService进行通信?我不知道如何将连接字符串传递给服务中的用户存储库.

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

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

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.
     }
}

解决方法

已经回答了问题,但我认为更好的答案是将存储库作为MembershipProvider的属性并在Application_Start中注入它.例如
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/

原文链接:https://www.f2er.com/aspnet/248062.html

猜你在找的asp.Net相关文章