Oauth with Dependency Injection

Asked

Viewed 77 times

0

Hello, I’m starting my studies with Oauth, and right away I came across a problem. I created the famous 'Startup' class, and in it I call my predecessor as follows:

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public void Configuration(IAppBuilder app)
    {
        app.UseOAuthBearerTokens(OAuthOptions);
    }

    static Startup()
    {
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/autenticar"),
            /*chamada do provider*/
            Provider = new OAuthProvider()
        };
    }

}

But the constructor of this class applies a dependency injection to the constructor as follows:

 IUsuariosServices _usuariosServices;

public OAuthProvider(IUsuariosServices usuariosServices)
{
    _usuariosServices = usuariosServices;
}

In order to be able to perform the functions inserted in this interface.

Thus remaining:

 public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    return Task.Factory.StartNew(() =>
    {
        string email = context.UserName;
        string senha = context.Password;
        /* Chamada da função da injeção de dependências */
        var usuario = _usuariosServices.Login(email, senha);
    });
}

But in my 'Startup' class, in the Provider class call an error occurs asking for a class parameter!

error message

inserir a descrição da imagem aqui

The problem is? What parameter is this? How to pass as a parameter an injection of dependencies? That’s what you have to do?

Thank you in advance...

1 answer

1


He’s waiting for an instance of IUsuariosServices, you set it here

IUsuariosServices _usuariosServices;

public OAuthProvider(IUsuariosServices usuariosServices)//Aqui diz que que o construtor base dela precisa de uma instância de IUsuariosServices 
{
    _usuariosServices = usuariosServices;
}

How to solve:

Passing an instance of IUsuariosServices for him

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public void Configuration(IAppBuilder app)
    {
        app.UseOAuthBearerTokens(OAuthOptions);
    }

    static Startup()
    {
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/autenticar"),
            /*chamada do provider*/
            Provider = new OAuthProvider(new UsuariosServices())//Estou supondo que a implementação de IUsuariosServices é UsuariosServices
        };
    }    
}

Possible problem depending on the architecture you are using your UsuarioService must wait for another instantiated object in it, the resolution is the same, pass the instance. I don’t know the architecture you’re using, but it might look something like this:

Provider = new OAuthProvider(new UsuariosServices(new UsuarioRepository(New SeuDbContext)()))

One of the ideas of using addiction injection is to get away from it.

Example consuming with and without dependency injection:

//Aqui é criada uma interface de repositorio
public interface ITesteRepository
{
    void Insert(Teste teste);
}

//Aqui é criada uma classe que irá implementar a interface ITesteRepository
public class TesteRepository : ITesteRepository
{
    public void Insert(Teste teste)
    {
        Context.Insert(teste)    
    }
}

//Aqui está sendo criado outra interface
public interface ITesteService
{
    void Insert(Teste teste);
}

//Aqui é criada uma classe que implementa a ITesteService
public class TesteService : ITesteService
{
    //Aqui estou criando via injeção de dependencia uma instancia do repositorio, pois vou usar ela em baixo
    private ITesteRepository _repositorioPorInjecao;
    public TesteService(ITesteRepository repositorioPorInjecao)
    {
        _repositorioPorInjecao = repositorioPorInjecao;
    }

    public void Insert(Teste teste)
    {
        _repositorioPorInjecao.Insert(teste);
    }
}

public class TestesController : Controller
{
    [HttpPost]
    public IActionResult Insert(Teste teste)
    {
        //Aqui estou criando SEM injeção de dependencia uma inetancia da service, note que o construtor base dela espera uma instancia de ITesteRepository por isso dei new em uma classe que implementa tal interface
        ITesteService serviceSemInjecao = new TesteService(new TesteRepository());
        serviceSemInjecao.Insert(Teste);
        return Json(new { Mensagem = "Sucesso!!" });
    }
}
  • In fact, this doesn’t make much sense, because I just pass an interface and there’s no way to initiate an interface. It is dependency injection, where I inform which class that interface represents and the instance of it is created in the constructor of the class that will use it

  • You’re not going to pass an interface, it turns out you need an instance that implements that interface. In the startup class there is no constructor, if not you could inject dependency there too

  • Could show an example?

  • @Guilhermenunes I added 1 example, I do not know if it was didactic, but I will try to improve the evening.

  • Aeh, boy, it worked fine, thank you very much.

  • @Guillhermenunes Wonder, if there is any doubt, I’m happy to try to answer ;)

Show 1 more comment

Browser other questions tagged

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