DCI: How to implement Context with Dependency Injection?

Posted by ciscoheat on Stack Overflow See other posts from Stack Overflow or by ciscoheat
Published on 2012-10-29T04:33:59Z Indexed on 2012/10/29 5:01 UTC
Read the original article Hit count: 152

Filed under:
|
|

Most examples of a DCI Context are implemented as a Command pattern. When using Dependency Injection though, it's useful to have the dependencies injected in the constructor and send the parameters into the executing method. Compare the Command pattern class:

public class SomeContext
{
    private readonly SomeRole _someRole;
    private readonly IRepository<User> _userRepository;

    // Everything goes into the constructor for a true encapsuled command.
    public SomeContext(SomeRole someRole, IRepository<User> userRepository)
    {
        _someRole = someRole;
        _userRepository = userRepository;
    }

    public void Execute()
    {
        _someRole.DoStuff(_userRepository);
    }
}

With the Dependency injected class:

public class SomeContext
{
    private readonly IRepository<User> _userRepository;

    // Only what can be injected using the DI provider.
    public SomeContext(IRepository<User> userRepository)
    {
        _userRepository = userRepository;
    }

    // Parameters from the executing method
    public void Execute(SomeRole someRole)
    {
        someRole.DoStuff(_userRepository);
    }
}

The last one seems a bit nicer, but I've never seen it implemented like this so I'm curious if there are any things to consider.

© Stack Overflow or respective owner

Related posts about c#

Related posts about dependency-injection