How to configure Ninject for MVC4 & custom Membership provide?

人盡茶涼 提交于 2019-11-29 12:14:42

I had a lot of trouble trying this and ended up adding a method that gets me a repository

using System.Web.Mvc;  //Used to access dependency resolver

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

I then call this in the methods that require it

I was able to get the repository to become injected using constructor injection but as soon as I went to use the repository the object had been disposed. I found the above to be the simplest alternative.

However, I guess you could also use the Initialize() method

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

Or another way would be to use a property

public IUserRepository UserRepository
{
    get
    {
        return DependencyResolver.Current.GetService<IUserRepository>();
    }
}

The result is always null. why? because asp.net has it's own static property for membership.

which is membership.provider. and this instance is not part of instance ninject management.

to workaround it , you need to use kernel.inject . but on the generate aspnetmvc.cs you would see that it's injection on PreApplicationStart event and won't let you.

here is the soloution by cipto that solve the problem for me. add this to your NinjectWebCommon

    [assembly: WebActivator.PreApplicationStartMethod(typeof(TopRankFantasy.App_Start.NinjectMVC3), "Start")]
    [assembly: WebActivator.PostApplicationStartMethod(typeof(TopRankFantasy.App_Start.NinjectMVC3), "RegisterMembership")]
    [assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(TopRankFantasy.App_Start.NinjectMVC3), "Stop")]

    public static void RegisterMembership()
    {
        bootstrapper.Kernel.Inject(Membership.Provider);
    } 

Link to article: Ninject and customMembership asp.net mvc 3

Since a custom RoleProvider often comes along with the custom MembershipProvider, in that case it is useful to add an injection for the Role Provider class. I used the ramon22's solution with an additional line.

[assembly: WebActivator.PreApplicationStartMethod(typeof(TopRankFantasy.App_Start.NinjectMVC3), "Start")]
[assembly: WebActivator.PostApplicationStartMethod(typeof(TopRankFantasy.App_Start.NinjectMVC3), "RegisterMembership")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(TopRankFantasy.App_Start.NinjectMVC3), "Stop")]

public static void RegisterMembership()
{
    bootstrapper.Kernel.Inject(Membership.Provider);
    bootstrapper.Kernel.Inject(Roles.Provider);
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!