jeudi 10 novembre 2016

Dependency Injection ASP.NET : Unaware about the dependencies until Runtime

I am using ASP.NET Core and using DI to build Hashing functionality. Since I don't know the type of hashing used at this stage (we are storing it in persistent storage). And Since Factory patterns violates DI as pointed by Steve. I am trying to avoid factories but still concerned about better way for this implementation.

The ICrypto Contract

public interface ICrypto
{
    string HashPassword(string plainPassword);
    bool VerifyHashedPassword(string hashedPassword, string providedPassword);     
}

I have several Implementations of ICrypto and they just wrap other libraries and provide the implementation of ICrypto Signatures. For example:

  • CryptoMD5
  • CryptoSHA1
  • CytpoOther

Now, in UserService I inject the ICyrpto to hash passwords for example:

Public class UserService
{
     ICrypto _crypto;

     public UserService(ICrypto crypto)
     {
         _crypto = crypto;
     }

    public bool Login (string username, string password)
    {   
        //code omitted
         var hash = _crypto.HashPassword(password);
    }
}

Adding Dependencies to the Container in Startup class

//get encryption type stored in cache, db or somewhere
   var cryptoType = //get param
   if (cryptoType  = "SHA1")
   {
       services.AddTransient<ICrypto, CryptoSHA1>();
   }
   else if (cryptoType  = "MD5")
   {
       services.AddTransient<ICrypto, CryptoMD5>();
   }

Is there more elegant way to this according to best practices?

Aucun commentaire:

Enregistrer un commentaire