Using dependency injection outside a controller with ninject

Asked

Viewed 475 times

3

I have following code:

public class ContaController : ApiController
{
    private readonly IAppServiceUsuario _app;

    public ContaController(IAppServiceUsuario _app)
    {
        this._app = _app;
    }
}

how to inject dependency with Ninject using that same IAppServiceUsuario in a class other than one Controller ?

It is mapped like this in Ninject:

kernel.Bind<IAppServiceUsuario>().To<AppServiceUsuario>();

Class that should be instantiated IAppServiceUsuario

 public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private IAppServiceUsuario _app;

        public AuthorizationServerProvider(IAppServiceUsuario _app)
        {
            this._app = _app;
        }

        /// <summary>
        /// Método para validar o token no cache do Oauth
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            context.AdditionalResponseParameters.Add("User", "");
            return Task.FromResult<object>(null);
        }

        /// <summary>
        /// Metodo para verificar as credenciais de acesso
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            if (_app.Autenticar(context.UserName, context.Password) != null)
            {
                Claim claim1 = new Claim(ClaimTypes.Name, context.UserName);
                Claim[] claims = new Claim[] { claim1 };
                ClaimsIdentity claimsIdentity =
                    new ClaimsIdentity(
                       claims, OAuthDefaults.AuthenticationType);
                context.Validated(claimsIdentity);
            }
            else
            {
                context.SetError("Erro na validação", "Usuario ou senha Inválidos");
            }
            return Task.FromResult<object>(null);
        }
    }
  • Eduardo, put this class and how it is instantiating, please?

  • 1

    added the class

  • Eduardo already tried to put in Ninject kernel.Bind<OAuthAuthorizationServerProvider>().To<AuthorizationServerProvider >(); to see if it works? you just forgot to mention how you’re instilling this? or this is the app that does?

  • Iappserviceusuario instancia ha Appserviceusuario

  • Yes Eduardo that I understood, but, as it passed to the builder of another class the Ninject needs to know to inject in her also so I asked Eduardo already tried to put in the Ninject kernel. Bind<Oauthauthorizationserverprovider>(). To<Authoriza tionServerProvider >();?

  • so I couldn’t

Show 1 more comment

1 answer

2

When vc makes the kernel. Bind(). To(), Ninject already injects dependency and when you call the class it creates it for you.

Example:

public class Repository : IRepository {
 ...
}

public class Domain : IDomain {    
  public Domain(IRepository repository){}   
  ...
}
public class AppService : IAppService { 
  public AppService (IDomain domain ){} 
   ...
}

public class SomeControllerController: ApiController{ 
  public SomeControllerController(IAppService appService){} 
  ...
}


kernel.Bind<IRepository>().To<Repository>();
kernel.Bind<IDomain>().To<Domain>();
kernel.Bind<IAppService>().To<AppService>();
  • yes in controller works perfectly but when I try to use outside of controller it fails to inject would use method contained in repository to authenticate user in another class

  • If you inject the dependency of what you need into the class you need ? Or can you put Ikernel as a dependency on your Domain for example, and instantiate for it what you need,If you inject the dependency of what you need into the class you need ? Or you can put Ikernel as a dependency on your Domain for example, and instantiate for it what you need; var teste = kernel.Get<IAlgumaCoisa>();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.