Injecting Dependencies into Domain Model classes with Nhibernate (ASP.NET MVC + IOC)

后端 未结 4 2329

I\'m building an ASP.NET MVC application that uses a DDD (Domain Driven Design) approach with database access handled by NHibernate. I have domain model class (Administrator) th

4条回答
  •  温柔的废话
    2021-02-09 11:26

    Is there a reason that you can't pass the IHashingService in the constructor for the Administrator class? That's how I would resolve the dependency.

    public class Administrator
    {
        private readonly IHashingService _hashingService;
    
        public Administrator(IHashingService hashingService)
        {
            _hashingService = hashingService;
        }
    
        // 
    
        public void SetPassword(string plainTextPassword)
        {
            this.HashedPassword = _hashingService.Hash(plainTextPassword);
        }
    }
    

    Edit #1

    If pulling from a model, try using method-level injection.

    public void SetPassword(string plainText, IHashingService hasher)
    {
        if (hasher == null) throw new ArgumentNullException("hasher");
        this.HashedPassword = hasher.Hash(plainText);
    }
    

    Edit #2

    Also, why not make it easy on yourself and just make an extension on string?

    public static class ExtensionsOfString
    {
        public static string Hash(this string s)
        {
            // hash with SHA256
            return hashedString;
        }
    }
    

    While I do realize that there's a "replaceable" code aspect of using dependency injection, this isn't exactly a big deal for this example. You don't really need a IPasswordEncryptionService the same way you'd need a, say, ICreditCardAuthorizationService. If, someday, you change your hashing algorithm from SHA256 to SHA512, you will now have invalidated every password in your database.

提交回复
热议问题