Inject repository to custom membership provider with Ninject

后端 未结 4 2036
走了就别回头了
走了就别回头了 2020-11-30 10:13

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]
         


        
4条回答
  •  情话喂你
    2020-11-30 10:31

    The problem is that the whole Membership infrastructure is a "native" .NET code (System.Web.Security) that does not know about MVC and about the DI container used by MVC. The static call to Membership.Provider returns the membership provider based on the configuration, however, the specified provider type is instantiated with a simple Activator.CreateInstance call. Hence, the dependency injection has no chance to kick in and set your repository dependency on the result. If you explicitly setup the returned instance with Ninject it can work, because you explicitly gave Ninject the object to set the dependencies. Even in this case it can only work with property injection and not with constructor injection, because the instance is created by the membership configuration previously.

    To summarize: you cannot easily inject dependencies into the membership provider because it is not resolved from a dependency injection container. I think you have 2 possibilities:

    1. You create a repository in the custom membership provider directly or you access it by some other means on demand (where the web context is already present).
    2. You go one level higher and check the components that would use your membership provider and you try change there (to use a membership provider resolved from your DI container instead of the uninitialized Memership.Provider). If this "higher component" is the forms authentication, then this article might be of help (using dependency injection with IFormsAuthentication and IMembershipService): http://weblogs.asp.net/shijuvarghese/archive/2009/03/12/applying-dependency-injection-in-asp-net-mvc-nerddinner-com-application.aspx

提交回复
热议问题