asp.net-mvc – 如何为MVC4配置Ninject并提供自定义成员资格?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何为MVC4配置Ninject并提供自定义成员资格?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
根据这篇文章描述 custom-membership-provider-with-repository-injection

我实现自定义成员资格提供注入.

定制会员提供商

using Ninject;

public class CustomMembershipProvider : MembershipProvider
{
        [Inject]
        public IUserRepository UserRepository { get; set; }

[...]

自定义角色提供者

using Ninject;

public class CustomRoleProvider : RoleProvider
{
      [Inject]
      public IUserRoleRepository UserRoleRepository { get; set; }
[...]

在Web.Config中

<membership defaultProvider="CustomsMembershipProvider">
      <providers>
        <clear/>
        <add name="CustomsMembershipProvider" type="namespace.CustomsMembershipProvider"/>
      </providers>
</membership>
<roleManager enabled="true" defaultProvider="customRoleProvider">
      <providers>
        <clear/>
        <add name="customRoleProvider" type="namespace.customRoleProvider"/>
      </providers>
</roleManager>

现在在NinjectWebCommon中

private static IKernel CreateKernel()
{
      var kernel = new StandardKernel();
      kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
      kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

      RegisterServices(kernel);
      return kernel;
}

private static void RegisterServices(IKernel kernel)
{
  [...]

  kernel.Bind<IUserRepository>().To<UserRepository>();
  kernel.Bind<IUserRoleRepository>().To<UserRoleRepository>();

  // Inject user & role repository into our custom membership & role providers.
   kernel.Inject(Membership.Provider);
   kernel.Inject(Roles.Provider);
}

当我运行应用程序时,我收到错误

This method cannot be called during the application’s pre-start
initialization stage.

来自kernel.Inject(Membership.Provider);这条线

但是如果我将内核设置放在Application_Start中

我得到了吼叫错误

Error activating IUserRepository No matching bindings are available,
and the type is not self-bindable. Activation path: 2) Injection of
dependency IUserRepository into property UserRepository of type
CustomMembershipProvider 1) Request for CustomeMembershipProvider

怎么解决这个问题. ??

解决方法

我在尝试这个时遇到了很多麻烦,最后添加了一个让我获得存储库的方法
using System.Web.Mvc;  //Used to access dependency resolver

    private IUserRepository GetUserRepository()
    {
        return DependencyResolver.Current.GetService<IUserRepository>();
    }

然后我在需要它的方法调用

我能够使用构造函数注入来获取注入库,但是一旦我去使用存储库,对象就被处理掉了.我发现上面是最简单的选择.

但是,我猜你也可以使用Initialize()方法

IUserRepository userRepository;
    public override void Initialize(string name,NameValueCollection config)
    {
        base.Initialize(name,config);
        this.userRepository = DependencyResolver.Current.GetService<IUserRepository>();
    }

或者另一种方式是使用财产

public IUserRepository UserRepository
{
    get
    {
        return DependencyResolver.Current.GetService<IUserRepository>();
    }
}
原文链接:https://www.f2er.com/aspnet/251037.html

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