Ninject setter方法返回null
本文关键字:null 返回 方法 setter Ninject | 更新日期: 2023-09-27 18:24:44
我正在尝试使用Setter方法进行注入。然而,我总是有一个空引用异常。
public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
private IMembershipService _membershipService;
[Inject]
public void SetMembershipService(IMembershipService membershipService)
{
_membershipService = membershipService;
}
//Code omitted
}
我不使用构造函数注入,因为CustomOAuth提供程序用于实例化OAuthAuthorizationServerOptions,在这种情况下,我必须以某种方式在构造函数中传递一个参数-
var oAuthServerOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth2/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat(ConfigurationManager.AppSettings["owin:issuer"])
};
Ninject模块-
Bind<IMembershipService>().To<MembershipService>();
要将某些东西注入到ninject未实例化的实例中,需要调用
kernel.Inject(..instance...);
在创建对象之后。为什么?Ninject不会神奇地知道对象是何时创建的。因此,如果它不是在创建对象本身,你需要告诉它关于对象的情况。
参考您的评论,这是绑定OAuthAuthorizationServerOptions
:的选项之一
Bind<OAuthorizationServerOptions>().ToConstant(new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth2/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = new CustomJwtFormat(
ConfigurationManager.AppSettings["owin:issuer"])
})
.WhenInjectedInto<CustomOAuthProvider>();
然后WhenInjectedInto
确保这些选项仅在创建CustomOAuthProvider
时使用。如果您总是(仅)使用CustomOAuthProvider
,则可能会删除When..
条件。