Ninject setter 方法 returns 空
Ninject setter method returns null
我正在尝试使用 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..
条件。
我正在尝试使用 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..
条件。