Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to inject a repository to a custom membership provider with ninject in MVC 3.

In MembershipProvider I have tried the following:

[Inject]
public ICustomerRepository _customerRepository{ get; set; }

And

[Inject]
public TUMembershipProvider(ICustomerRepository customerRepository)
{
    _customerRepository = customerRepository;
}

In my ninject module i tried the following:

Bind<MembershipProvider>().ToConstant(Membership.Provider);

None of the above works.

When i use(in global.asa)

kernel.Inject(Membership.Provider);

together with

[Inject]
public ICustomerRepository _customerRepository{ get; set; }

it works, but i have no life cycle management and this will cause a "ISession is open" error from NHibernate, because the ISession is InRequestScope and the repository is not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
559 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could use the approach @Remo Gloor outlines in his blog post on provider injection. It involves 3 steps:

  1. Add [Inject]s to any properties on your provider you need injected (although the pattern he shows -- creating a very simple class whose only function is to be a receptable for property injection and forwards any requests to a real class implemented using constructor injection -- is well worth following)

    public class MyMembershipProvider : SqlMembershipProvider
    {
        [Inject]
        public SpecialUserProvider SpecialUserProvider { get;set;}
        ...
    
  2. Create an initializer wrapper that implements IHttpModule which pulls the provider in, triggering its creation:-

    public class ProviderInitializationHttpModule : IHttpModule
    {
        public ProviderInitializationHttpModule(MembershipProvider membershipProvider)
        {
        }
    ...
    
  3. Register the IHttpModule in your RegisterServices :-

    kernel.Bind<IHttpModule>().To<ProviderInitializationHttpModule>();
    
  4. there is no 4; Ninject does the rest - bootstrapping all registered IHttpModules including the one you added) during the startup sequence.

(Don't forget to read the comments on the blog post re lifetimes etc.)


Finally, if you're looking for something completely braindead direct that solves it neatly, try this @Remo Gloor answer instead


PS a great writeup on the whole mess is Provider is not a Pattern by @Mark Seemann. (and the oboligatory plug for his excellent book:- Dependency injection in .NET which will have you figuring this stuff out comfortably from first principles)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...