问题描述
我正在尝试使用 MVC 3 中的 ninject 将存储库注入到自定义成员资格提供程序.
I'm trying to inject a repository to a custom membership provider with ninject in MVC 3.
在 MembershipProvider 中,我尝试了以下操作:
In MembershipProvider I have tried the following:
[Inject]
public ICustomerRepository _customerRepository{ get; set; }
和
[Inject]
public TUMembershipProvider(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
在我的 ninject 模块中,我尝试了以下操作:
In my ninject module i tried the following:
Bind<MembershipProvider>().ToConstant(Membership.Provider);
以上都不起作用.
当我使用(在 global.asa 中)
When i use(in global.asa)
kernel.Inject(Membership.Provider);
一起
[Inject]
public ICustomerRepository _customerRepository{ get; set; }
它可以工作,但我没有生命周期管理,这会导致 NHibernate 出现ISession 已打开"错误,因为 ISession 是 InRequestScope 而存储库不是.
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.
推荐答案
你可以使用@Remo Gloor 在他关于提供者注入的博文中概述了.它包括 3 个步骤:
You could use the approach @Remo Gloor outlines in his blog post on provider injection. It involves 3 steps:
将
[Inject]
添加到您需要注入的提供程序上的任何属性(尽管他展示的模式 - 创建一个非常简单的类,其唯一的功能是接受属性注入并将任何请求转发到使用构造函数注入实现的真实类 - 非常值得关注)
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;}
...
创建一个实现了 IHttpModule
的初始化包装器,它拉入提供者,触发它的创建:-
Create an initializer wrapper that implements IHttpModule
which pulls the provider in, triggering its creation:-
public class ProviderInitializationHttpModule : IHttpModule
{
public ProviderInitializationHttpModule(MembershipProvider membershipProvider)
{
}
...
在您的 RegisterServices
中注册 IHttpModule
:-
kernel.Bind<IHttpModule>().To<ProviderInitializationHttpModule>();
没有4;Ninject 完成剩下的工作 - 在启动序列期间引导所有已注册的 IHttpModules
,包括您添加的那个).
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.)
最后,如果您正在寻找可以巧妙解决问题的完全脑残的直接方法,请尝试这个@Remo Gloor 答案
Finally, if you're looking for something completely braindead direct that solves it neatly, try this @Remo Gloor answer instead
PS 一篇关于整个混乱的很棒的文章是 Provider is not a Pattern by@马克西曼.(以及他优秀著作的强制插件:- .NET 中的依赖注入,这将使您弄清楚这些东西从第一原则舒适)
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)
这篇关于使用 Ninject 将存储库注入自定义成员资格提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!