Showing posts with label unity. Show all posts
Showing posts with label unity. Show all posts

Friday, August 12, 2011

On Dependency Injection and Violating Encapsulation Concerns

For me, life is greatly simplified when dependencies are inverted and constructor injection is used to provide a clean mechanism to introduce dependencies to a class. It's explicit and easy to test.

Others however argue that some dependencies are private implementation details to the class and external callers shouldn't know about them. The argument is that exposing these dependencies through the constructor violates encapsulation and introduces coupling. This argument is usually coupled with resistance to using interfaces or classes with virtual methods.

From my experience, there are times when composition in the constructor makes sense but there's a fine line when constructor injection should be used. I want to use this post to elaborate on these arguments and provide my perspective on this debate.

Does Constructor Injection violate Encapsulation?

Does exposing the internal dependencies of a class in the constructor expose the implementation details of a class? If you are allowing callers to construct the class directly, then you are most certainly breaking encapsulation as the callers must posses the knowledge of how to construct your class.  However, regardless of the constructor arguments if callers know how to construct your class you are also coupling to a direct implementation and will undoubtedly create a test impediment elsewhere. There are some simple fixes for this (including more constructor injection or another inversion of control technique) which I'll outline later.

So if constructor injection violates encapsulation, when is it safe to use composition in the constructor?

It really depends on the complexity and relationship of the subject to its dependencies. If the internal dependencies are simple and contain no external dependencies there is likely no harm in using composition to instantiate them in the constructor (the same argument can be made for small static utility methods). For instance, a utility class that performs some translation or other processing activity with limited outcomes may work as a private implementation detail. Problems arise as soon as these dependencies take on further dependencies or produce output that influences the conditional logic of the subject under test. When this happens the argument to keep these as internally controlled dependencies becomes flawed and it may be necessary to upgrade the "private implementation detail" to an inverted dependency.

Before:

This example shows a class that has a private implementation detail that influences logic of the subject under test. The consequence of this design is that the internal details of the validator leak into the test specifications. This leads to very brittle tests as tests must concern themselves with object construction and validation rules -- any change to the object or validation logic will break the tests.

public class MyModelTranslator
{
    public MyModelTranslator()
    {
       _validator = new MyModelValidator();
    }

    public MyViewModel CreateResult(MyModelObject model)
    {
        var result = new MyViewModel();
        
        if (_validator.Validate( model ));
        {
             result.Id = model.Id;
        }
        else {
            result.State = MyResultState.Invalid;
        }
        return result;
    }
}

[Test]
public void WhenCreatingAResult_FromAVaidModelObejct_ShouldHaveSameId()
{
    var subject = new MyModelTranslator();

    // create model object with deep understanding how Id's
    // and expiry dates are related 
    var model = new MyModelObject()
    {
        Id = "S1402011"
        Expiry = Datetime.Parse("12/31/2011");
    };
    var result = subject.CreateResult( model );
    Assert.AreEqual("S1402011", result.Id);
}

After:

This example shows the above example corrected to use a constructor injected dependency that can be mocked. In doing so, the test is not encumbered with object creation or validation details and can easily simulate validate states without introducing brittleness.

public class MyModelTranslator
{
    public MyModelTranslator(MyModelValidator validator);
    {
       _validator = validator;
    }

    // ...
}

[Test]
public void WhenCreatingAResult_FromAVaidModelObejct_ShouldHaveSameId()
{
    var validatorMock = new Mock<MyModelValidator>();

    var subject = new MyModelTranslator(validatorMock.Object);
    var model = new MyModelObject()
    {
      Id = "Dummy"
    };

    // we no longer care how validation is done, 
    // but we expect validation to occur and can easily control
    // and test outcomes
    ValidatorMock.Setup( x => x.Validate( model )).Returns( true );

    var result = subject.CreateResult( model );
    Assert.AreEqual("Dummy", result.Id);
}

Combatting Coupling with Inversion of Control

As the above points out, if we expose the dependencies of a class in the constructor we move the coupling problems out of the class and into the callers. This is not good but it can easily resolved.

An example that shows that our controller class now knows about the MyModelValidator:

public class MyController
{
    public MyController()
    {
        _translator = new MyModelTranslator( new MyModelValidator() );
    }
}

More Constructor Injection

Ironically, the solution for solving coupling and construction problems is more constructor injection. This creates a Russian Doll where construction logic is deferred and pushed higher and higher up the stack resulting in a top level component which is responsible for constructing the entire object graph. While this provides an intuitive API that clearly outlines dependencies, it's tedious to instantiate by hand. This is where dependency injection  frameworks like Unity, StructureMap and others come in: they can do the heavy lifting for you. If done right, your application should only have well defined points where the dependency container is used.

public class MyController : IController
{
    public MyController(MyModelTranslator translator)
    {
        _translator = translator;
    }
}

Note that this assumes that the constructor arguments are abstractions -- either interfaces, abstract classes or classes with virtual methods. In effect, by exposing the constructor arguments we trade off the highly sealed encapsulated black box for an open for extensibility model.

Factories / Builders

In some cases, using Constructor Injection everywhere might not be a good fit. For example, if you had a very large and complex object graph, creating everything upfront using constructor injection might represent a performance problem. Likewise, not all parts of the object graph will be used immediately and you may need to defer construction until needed.  In these cases, the good ol' Gang of Four Factory pattern is a handy mechanism to lazy load components.

So rather that construct the entire object graph and pass resolved dependencies as constructor arguments, pass the factory instead and create the lower-level sub-dependencies when needed.

public class MyControllerFactory : IControllerFactory
{
    private IUnityContainer _container;
    
    public MyControllerFactory(IUnityContainer container)
    {
        _container = container;
    }

    public IController Create()
    {
        _container.Resolve<MyController>();
    }
}

Service Location

While Service Location is an effective mechanism for introducing inversion of control, I'm listing it last for a reason. Unlike Constructor Injection, Service Location couples all your code to an intermediate provider. Depending on your application and relative complexity this might be acceptable, but from personal experience it's a very slippery slope -- actually, it would be more appropriate to call it a cliff because removing or replacing the container from an existing codebase can be a massive undertaking.

I see service location as a useful tool when refactoring legacy code towards Constructor Injection. The lower "leaf-nodes" of the object graph can take advantage of constructor injection and the higher nodes can temporarily use service location to create the "leaves". As you refactor, the service locator is removed and replaced with constructor injection, which results in an easier to test and discoverable API. This also provides a pragmatic bottom up refactor approach.

Summary

  • Use "new" when dependencies have no external dependencies or don't influence conditional flow of the subject.  Conversely, use constructor injection when dependencies have additional dependencies.
  • Use an IoC container to construct objects that use constructor injection, but only use the IoC container in high level components that are responsible for construction of the object graph. If constructing the entire object graph is a performance concern, consider encapsulating the container in a Factory that can be used to resolve remaining parts of the object graph when needed.
  • To prevent violating encapsulation concerns, use inversion of control to promote using abstractions instead of concrete dependencies.

submit to reddit

Thursday, January 07, 2010

Twelve Days of Code – Unity Framework

As part of the twelve days of code, I’m building a Pomodoro style task tracking application and blogging about it. This post is the seventh in this series. This post focuses on using the Microsoft Unity Framework in our .NET 4.0 application.

This post assumes assumes that you are familiar with the last few posts and have a working understanding of Inversion of Control.  If you’re new to this series, please check out some of the previous posts and then come back.  If you’ve never worked with Inversion of Control, it’s primarily about decoupling objects from their implementation (Factory Pattern, Dependency Injection, Service Locator) – but the best place to start is probably here.

Overview

Our goal for this post is to remove as many hard-code references to types as possible.  Currently, the constructor of our MainWindow initializes all the dependencies of the Model and then manually sets the DataContext.  We need to pull this out of the constructor and decouple the binding from TaskApplicationViewModel to ITaskApplication.

Initializing the Container

We’ll introduce our inversion of control container in the Application’s OnStartup event.  The container’s job is to provide type location and object lifetime management for our objects, so all the hard-coded initialization logic in the MainWindow constructor is registered here.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        IUnityContainer container = new UnityContainer();
        
        container.RegisterType<ITaskApplication, TaskApplicationViewModel>();
        container.RegisterType<ITaskSessionController, TaskSessionController>();
        container.RegisterType<IAlarmController, TaskAlarmController>();
        container.RegisterType<ISessionRepository, TaskSessionRepository>();

        Window window = new MainWindow();
        window.DataContext = container.Resolve<ITaskApplication>();
        window.Show();

        
        base.OnStartup(e);
    }
}

Also note, we’re initializing the MainWindow with our data context and then displaying the window.  This small change means that we must remove the MainWindow.xaml reference in the App.xaml (otherwise we’ll launch two windows).

Next Steps

Aside from the simplified object construction, it would appear that the above code doesn’t buy us much: we have roughly the same number of lines of code and we are simply delegating objection construction to Unity.  Alternatively, we could move the hard-coded registrations to a configuration file (though that’s not my preference here).

In the next post, we’ll see how using Prism’s Bootstrapper and Module configuration allows us to move this logic into their own modules.

In the next step, we’ll look at using P

submit to reddit

Tuesday, December 15, 2009

Unity, Dependency Injection and Service Locators

For a while now, I’ve been chewing on some thoughts about the service locators versus dependency injection, but struggled to find the right way to say it.  I sent an email to a colleague today that tried to describe some of the lessons learned from my last project.  It comes close the visceral feelings I have around this subject, but describes it well.  Here it is unaltered:

When you pull dependencies in from the Container, you’re using a Service Locator feature of Unity; When you push dependencies in via the constructor, you’re using Dependency Injection.  There’s much debate over which pattern to use.  When using dependency injection, the biggest advantage is that the relationship between objects is well known.  This helps us understand the responsibilities of each object better, may have better performance (if we’re resolving dependencies a lot) and it makes it easier to write tests that isolate the behavior of the subject under test.

In a project where we’re resolving dependencies at runtime, the true nature of the dependencies between objects is obscured -- developers must read through the source to understand responsibilities.  Each time a change is made to resolve new dependencies from the container, the tests will fail.  Since locating and understanding the responsibility of the dependencies in the source is a complex task, the easy solution is to simply register the missing dependencies in the container and move on.  In most cases, the object that is registered is the concrete implementation which is also susceptible to the same dependency problem.  Ultimately, this compounds the problem until the tests themselves become obscured, vague, incomplete or overly complex.

In contrast, if the dependencies were registered in the constructor, all dependencies are known at compile time.  Any changes made to the subject won’t compile until the tests are updated to reflect the new functionality.  Note that because the object doesn’t use the container, the tests become just like any other simple POCO test.

This is not a silver bullet solution however.  There are times when resolving from the container makes sense – loaders and savers, for example – but even then, the container can be hidden inside a POCO factory. In contrast to service location, the impact of constructor injection is that it may require more work upfront to realize the dependencies, though this can be mitigated in some cases using a TDD methodology where the tests satisfy the responsibilities of the subject under test as it is written.

Comments welcome.

submit to reddit

Tuesday, November 10, 2009

Implementing a Strategy Pattern using the Unity Framework

My current project is using Unity and has had some interesting challenges to work through.  One of the design challenges we encountered involved several components that were nearly identical in appearance except for a few minor functional details.  We decided to implement a strategy pattern where the variances were different strategies that were applied to common context.

For the sake of argument, let’s say we’re talking about a Financial Calculator that supports different types of financial calculations (FPV, Payment, etc)

public class Calculator : ICalculator
{
    public Calculator(IFormula formula)
    {
	_formula = formula;
    }

    public CalcResult Calculate(CalcArgs input)
    {
        return _formula.Process(input);
    }

    IFormula _formula;
}

public interface IFormula
{
    CalcResult Process(CalcArgs input);
}

public class FutureValue : IFormula
{
    public CalcResult Process(CalcArgs input)
    {
        // ...
    }
}

public class PresentValue: IFormula
{
    public CalcResult Process(CalcArgs input)
    {
        // ...
    }
}

In my last post, I showed how Unity needs some additional configuration in order to resolve ambiguous types – Unit won’t be able to resolve our Calculator unless we specify which IFormula we want to use.  This scenario is a bit different because we want to be able to use both the FutureValue and PresentValue formulas at runtime. 

We have a couple of options to choose from, each with their own pitfalls:

  • Container overloading
  • Named Instances

Container Overloading

At a basic level, we’re limited to registering a type only once per container.  Fortunately, Unity supports the ability to spawn a child container that can used to replace registered types with alternate registrations.  By swapping out our types, we can create alternate runtimes that can be scoped to specific areas of our application.

[TestMethod]
public void CanOverloadContainer()
{
    // create the container and register the
    //    PresentValue formula
    var container = new UnityContainer();
    container.RegisterType<IFormula, PresentValue>();

    // verify we can resolve PresentValue
    var formula1 = container.Resolve<IFormula>();
    Assert.IsInstanceOfType(formula1, typeof(PresentValue));

    // create a child container, and replace
    //    the formula with FutureValue formula
    var childContainer = container.CreateChildContainer();
    childContainer.RegisterType<IFormula, FutureValue>();

    // verify that we resolve the new formula
    var formula2 = childContainer.Resolve<IFormula>();
    Assert.IsInstanceOfType(formula2, typeof(FutureValue));
}

This approach provides a clean separation between the container and the various combinations of our strategy pattern.  If you can compose your application of controllers that can extend and manipulate child containers, this is your best bet as each container provides a small targeted service to the application as a whole.

However, if the variations must live in close contact with one another and you can’t separate them into different containers, you’ll need a different strategy.

Named Instances

Unity provides the ability to register a type more than once, with a caveat that each type is given a unique name within the container.  This feels more like a hack than a best practice, but it provides a simple solution to registering the various combinations of ICalculator types side-by-side.  Since our variations are based on the types passed in through the constructor, we can provide Unity the construction information it needs using InjectionConstructor and ResolvedParameter objects.  To resolve our objects, we must specify the unique name when resolving.

[TestMethod]
public void CanConstructUsingConstructorInfo()
{
    var container = new UnityContainer();

    container.RegisterType<ICalculator, Calculator>("FutureValue",
                            new InjectionConstructor(new ResolvedParameter<FutureValue>())
                            );

    container.RegisterType<ICalculator, Calculator>("PresentValue",
                            new InjectionConstructor(new ResolvedParameter<PresentValue>())
                            );

    var calc1 = container.Resolve<ICalculator>("FutureValue");
    var calc2 = container.Resolve<ICalculator>("PresentValue");
}

At this point, I need to step aside and point out that there is a potential problem with this approach.  We’ve created a mechanism that allows our type to be easily resolved directly from the container using it’s unique name.  There is temptation to pass the container into our code and resolve these objects by name.  This is a slippery slope that will quickly tie your application code and tests directly to Unity.  I will blog more about this in an upcoming post, but here are some better alternatives:

Resolved Parameters

Rather than manually resolving the named instance from the container, configure the container to use your named instance:

public class Example
{
    public Example(ICalculator calculator)
    {
        Calculator = calculator;
    }

    public ICalculator Calculator
    {
        get;
        set;
    }
}

[TestClass]
public class ExampleTest
{
    [TestMethod]
    public void ConfigureExampleForNamedInstance()
    {
        var container = new UnityContainer();
        container.RegisterType<ICalculator, Calculator>("FutureValue",
                                    new InjectionConstructor(
                                            new ResolvedParameter<FutureValue>())
                                    );

        container.RegisterType<Example>(
                                    new InjectionConstructor(
                                            new ResolvedParameter<ICalculator>("FutureValue"))
                                    );

        Example ex = container.Resolve<Example>();
    }
}
Dependency Attributes

Unity supports special attributes that can be applied to your code to provide configuration guidance.  This can make instrumenting your code much easier, but it has a downside of brining the dependency injection framework into your code.  This isn’t necessarily the end of the world, but can limit us if we want to reuse this class with a different dependency or overload it in another container.

public class Example
{
    public Example(
                [Dependency("FutureValue")]
                ICalculator calculator
                  )
    {
        Calculator = calculator;
    }

    public ICalculator Calculator
    {
        get;
        set;
    }
}

Alternatively, the DependencyAttribute can be applied to Properties as well for Setter injection.  Personally, I find this reads better than using attributes in the constructor, and I’ll save my points about Setter injection for another post.

public class Example
{
    [Dependency("FutureValue")]
    public ICalculator Calculator
    {
        get; set;
    }
}

Conclusion

Although inversion of control promotes use of interfaces to decouple our implementations, we often use abstract classes and composition to construct our objects.  In the case of composition, we need to provide Unity with the appropriate information to construct our objects.  Wherever possible, we should defer construction logic to configuration settings rather than instrumenting the code with container information.

submit to reddit

Monday, November 09, 2009

Simple Dependency Injection using the Unity Framework

My current project is using Unity as an Inversion of Control / Dependency Injection framework.  We’ve had a few challenges and lessons learned while using it.  This is my first post on the topic, and I want to provide a quick look:

Unity is slightly different than most dependency injection frameworks that I’ve seen.  Most dependency injection frameworks, such as Spring.NET (when I last used it), require you to explicitly define the dependencies for your objects in configuration files.  Unity also uses configuration files, but it also can construct any object at runtime by examining its constructor.

Let’s take a simple example where I have a product catalog service that provides simple searching for products by category.  The service is backed by a simple and crude ProductRepository object.

public class ProductCatalog
{
    public ProductCatalog(ProductRepository repository)
    {
        _repository = repository;
    }

    public List<Product> GetProductsByCategory(string category)
    {
        return _repository.GetAll()
                          .Where(p => p.Category == category)
                          .ToList();
    }

    private ProductRepository _repository;
}

public class ProductRepository
{
    public ProductRepository()
    {
        _products = new List<Product>()
            {
            new Product() { Id = "1", Name = "Snuggie", Category = "Seen on TV" },
            new Product() { Id = "2", Name = "Slap Chop", Category = "Seen on TV" }
            };
    }

    public virtual List<Product> GetAll()
    {
        return _products;
    }

    private List<Product> _products;
}

public class Product
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
}

With no configuration whatsoever, I can query Unity to resolve my ProductCatalog in a single line of code.  Unity will inspect the constructor of the ProductCatalog and discover that it is dependent on the ProductRepository.  Since the ProductRepository does not require any additional dependencies in its constructor, Unity will construct the repository and assign it to the catalog for me.

[Test]
public void CanResolveWithoutConfiguration()
{
    var container = new Microsoft.Practices.Unity.UnityContainer();

    var catalog = container.Resolve<ProductCatalog>();

    var products = catalog.GetProductsByCategory("Seen on TV");

    Assert.AreEqual(2, products.Count);
}

Aside from the fact that this is a crude example, a production system would be extremely limited because the product catalog is tightly coupled to our repository implementation.  Although we could subclass the product repository, a better solution would decouple the two classes by introducing an interface for the product repository.

public interface IProductRepository
{
    List<Product> GetAll();
}

public class ProductRepository : IProductRepository
{
    // ...
}

public class ProductCatalog
{
    public ProductCatalog(IProductRepository repository)
    {
        // ...
    }

    // ...
}

This is a much more ideal solution as our components are now loosely coupled, but Unity no longer has enough information to automatically resolve the ProductCatalog’s dependencies.  To fix this issue, we need to provide this information to the Unity container.  This can be done through configuration files, or by manipulating the container directly:

[Test]
public void CanResolveWithRegisteredType()
{
    var container = new Microsoft.Practices.Unity.UnityContainer();
    
    container.RegisterType<IProductRepository, ProductRepository>();

    var catalog = container.Resolve<ProductCatalog>();

    var products = catalog.GetProductsByCategory("Seen on TV");

    Assert.AreEqual(2, products.Count);
}

Note that while I’m using the Unity container in my tests, it's completely unnecessary. I can simply mock out my dependencies (IProductRepository), pass them in, and test normally.

Conclusion

This demonstrates how Unity is able to resolve simple types without extensive configuration.  By designing our objects to have their dependencies passed in they possess no knowledge of the dependency injection framework, making them lean, more portable and easy to test.

submit to reddit