OAuth with Dependency Injection

0

Hello, I'm starting my studies with OAuth, and right away I came across a problem. I created the famous 'Startup' class, and I call it my provider 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 in the constructor as follows:

 IUsuariosServices _usuariosServices;

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

In order to perform the functions inserted in this interface.

Looking like this:

 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 call of the provider class an error occurs asking for a parameter of the class!

error message

The problem is? What is this? How to pass dependency injection as a parameter? Is that what you have to do?

Thank you in advance ...

    
asked by anonymous 10.05.2018 / 15:36

1 answer

1

It's expecting 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 resolve:

Passing an instance of IUsuariosServices to it

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 should expect another object instantiated in it, the resolution is the same, pass the instance. I do not know the architecture you are using, but it might look something like this:

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

One of the ideas of using dependency 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!!" });
    }
}
    
10.05.2018 / 15:50