Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) that I want to inject a dependency into via an IOC Container such as Castle Windsor, something like this:

public class Administrator
{
    public virtual int Id { get; set; }

    //.. snip ..//

    public virtual string HashedPassword { get; protected set; }

    public void SetPassword(string plainTextPassword)
    {
        IHashingService hasher = IocContainer.Resolve<IHashingService>();

        this.HashedPassword = hasher.Hash(plainTextPassword);
    }
}

I basically want to inject IHashingService for the SetPassword method without calling the IOC Container directly (because this is suppose to be an IOC Anti-pattern). But I'm not sure how to go about doing it. My Administrator object either gets instantiated via new Administrator(); or it gets loaded via NHibernate, so how would I inject the IHashingService into the Administrator class?

On second thoughts, am I going about this the right way? I was hoping to avoid having my codebase littered with...

currentAdmin.Password = HashUtils.Hash(password, Algorithm.Sha512);

...and instead get the domain model itself to take care of hashing and neatly encapsulate it away. I can envisage another developer accidently choosing the wrong algorithm and having some passwords as Sha512, and some as MD5, some with one salt, and some with a different salt etc. etc. Instead if developers are writing...

currentAdmin.SetPassword(password);

...then that would hide those details away and take care of those problems listed above would it not?

like image 919
Sunday Ironfoot Avatar asked Jan 13 '10 00:01

Sunday Ironfoot


1 Answers

There are already similar questions here on SO:

Dependency injection with NHibernate objects

DI/IoC, NHibernate and help in getting them to work together

You'll need to use Interceptors. Take a look at Fabio Maulo's post for implementation:

http://nhforge.org/blogs/nhibernate/archive/2008/12/12/entities-behavior-injection.aspx

like image 99
Miroslav Popovic Avatar answered Nov 15 '22 11:11

Miroslav Popovic