Search code examples
c#ninjectasp.net-identity-2ninject.web.mvc

Ninject Bind IIdentityMessageService twice


I hope you are doing well with everything.

I am trying to seperate the asp.net identity UserManger implementation from the default implementation that comes with the project template. For DI I am using Ninject (I am new to Ninject)

Now I have something like this...

 kernel.Bind<UserManager<User>>().To<UserManager>().InRequestScope();
 kernel.Bind<IUserTokenProvider<User, string>>().ToMethod(x =>
 {
     var provider = OwinConfig.DataProtectionProvider;
     return new DataProtectorTokenProvider<User>(provider.Create("ASP.NET Identity"));
 }).InRequestScope();


 kernel.Bind<SignInManager>()
       .ToSelf()
       .InRequestScope();

I am trying to register the SmsService and EmailService that implement IIdentityMessageService

I am doing something like this ---- and it is not working with ninject

kernel.Bind<IIdentityMessageService>().To(typeof (SmsService)).InRequestScope();
kernel.Bind<IIdentityMessageService>().To(typeof (EmailService)).InRequestScope();

Error activating IIdentityMessageService More than one matching bindings are available.

......

Suggestions: 1) Ensure that you have defined a binding for IIdentityMessageService only once.

Now as said before I moved the usermanager to a seperate library and the constructor for my UserManger is

public UserManager(Context context, IIdentityMessageService emailService, 
    IIdentityMessageService smsService, IUserTokenProvider<User, string> tokenProvider = null)
    : base(new UserStore(context))

So my question is, how can I achieve to inject IIdentityMessageService twice or how to construct UserManager with ninject?


Solution

  • The solution is to use named bindings:

    kernel.Bind<IIdentityMessageService>().To(typeof (SmsService)).Named("Sms");
    kernel.Bind<IIdentityMessageService>().To(typeof (EmailService)).Named("Email");
    

    And then resolve it via attributes:

    public UserManager(Context context, 
                      [Named("Email")] IIdentityMessageService emailService,
                      [Named("Sms")] IIdentityMessageService smsService, 
                      IUserTokenProvider<User, string> tokenProvider = null)
       : base(new UserStore(context))