1

I'm using Microsoft.Practices.ObjectBuilder in a web project to handle dependency injection (between view and presenter for example).

I've recently added an ASP.NET Web Service (.asmx) to handle ajax calls. I would like to use dependency injection with ObjectBuilder here as well, but I can't get it working.

I tried to just simply add something like this:

[CreateNew]
public MyClass MyClass
{
    set
    {
        _myClass = value;
    }
}

But this isn't working. The property setter of MyClass is never called. Is it even possible to get this working?

Joel
  • 8,502
  • 11
  • 66
  • 115
  • To answer the question, yes it is probably possible. – Dennisch Aug 19 '13 at 14:08
  • ObjectBuilder? Seriously? Why do you use this obscure peace of technology that is used to build DI containers with? Why don't you simply use Unity (that's built on top of ObjectBuilder)? – Steven Aug 19 '13 at 17:13
  • You will have to implement your own HandlerFactory, but even than, ASP.NET is in control of creating your handler, so it needs a default constructor. What you can try is explicit property injection (dependency property marked with an attribute) and a custom HandlerFactory that builds up the fsctory. But no idea how to do this with ObjectBuilder. – Steven Aug 19 '13 at 17:17
  • @Steven, I don't have much of a choice. Old legacy system, trying to avoid major refactoring just to get this thing working. I could use Unity, but I'm trying to keep changes to a minimum in this part of the project – Joel Aug 20 '13 at 05:45

1 Answers1

0

Regarding to old legacy system, especially for those using static - stateless classes, I found this design to be the most fit:

public MyClass MyClass
{
    get
    {
        if(_myClass == null){ _myClass = new DefaultMyClass(); }
        return _myClass;
    }
    set
    {
        _myClass = value;
    }
}

With this, I can still do dependency injection in unit test, using setter injection.

IMyClassUser m = new MyClassUser();
m.MyClass = new MockMyClass();

While, at the very point, does not change the existing code too much. And later when the times come, it can be modified using constructor DI.

It will also help your legacy colleague whom does not understand DI too much, to able to track the code faster (using Go to Definition). And it can survive even without interface/class documentation.

Fendy
  • 4,565
  • 1
  • 20
  • 25