如何通过覆盖的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()); }
我在这里写了一个更深入的解释: