Reputation: 519
I'm trying to make an injection using Setter Method. However what I always have is a null reference exception.
public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
private IMembershipService _membershipService;
[Inject]
public void SetMembershipService(IMembershipService membershipService)
{
_membershipService = membershipService;
}
//Code omitted
}
I'm not using constructor injection because CustomOAuth provider is used in instantiating OAuthAuthorizationServerOptions, and in this case I would have to pass a parameter in constructor somehow -
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 module -
Bind<IMembershipService>().To<MembershipService>();
Upvotes: 0
Views: 304
Reputation: 13233
To inject something into an instance which is not instanciated by ninject, you need to call
kernel.Inject(..instance...);
after the object has been created. Why? Ninject does not magically know when objects are created. So if it's not creating the object itself, you need to tell it about the object.
referring to your comment, this is one of the options to bind 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>();
Then WhenInjectedInto
makes sure these options are only used when creating an CustomOAuthProvider
. In case you're always (only) using the CustomOAuthProvider
you can probably remove then When..
condition.
Upvotes: 1