c# – How to use dependency injection outside a Controller with ninject

Question:

I have the following code:

public class ContaController : ApiController
{
    private readonly IAppServiceUsuario _app;

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

how to inject dependency with Ninject using this same IAppServiceUsuario in another class that is not a Controller ?

It is mapped like this on Ninject :

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

Class that where IAppServiceUsuario should instantiate

 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);
        }
    }

Answer:

When you do 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>();
Scroll to Top