Newbie: best practice to resolve a lot of interfaces

Apr 6, 2011 at 4:31 PM

Hi guys,

I'm starting with Unity and working on a project with several layers. With MVP and Unit Testing. For this, we are using Unity to resolve the interfaces.

But I find that a little tedious: A huge amount of interfaces through a lot of classes have to be resolved and takes about 20 lines of code in each class for each interface! Most of the code repeated. And the unity.config will end up having > 50 <types> entries.

  1. Is there a way to tell a interface (or abstract class) to resolve itself?
  2. Is there a way to tell Unity (or to extend it) so it can "guess" the class that implements the interface? (asumming there is only one class in the current app that implements the interface, of course)

What I have in a typical presenter class:

        IView.IExclusiones _iView { get; set; }
        IView.IExclusiones iView
                if (_iView == null)
                    UnityContainer container = new UnityContainer();
                    UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                    _iView = container.Resolve<IView.IExclusiones>();

                return iView;
                iView = value;

Am I missing something?

Thanks for your time! (and for your pacience also)

Apr 7, 2011 at 1:03 AM

You should not have a UnityContainer object inside your presenter class.  Doing so creates a hard dependency on the container and defeats the purpose of dependency injection.  In this case, you should mark the iView property as a dependency of the presenter and through property configuration of the class, the unity container will be able to automatically inject it as a dependency.  You can do so through property or constuctor injection.  I believe this will answer your first question; you won't need to explicitly call Resolve in order to obtain an instance of that interface. Check out how to do injection here which is part of the documentation.  It can also be done in the config instead of attributes, you can refer to this topic.

As for your second question, there's no built-in feature of Unity which allows you to do this.  But you may want to check out the Unity Auto Registration also available here in CodePlex.


Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.

Apr 8, 2011 at 1:19 PM

I will look into the links you provided and see what can I make out of them.

Thanks a lot for your kind reply.

Apr 9, 2011 at 6:16 AM

Since you're new to the whole DI think, I'd strongly recommend getting a copy of Mark Seeman's book "Dependency Injection in .NET" from Manning Press. It's still in early access, but I've read it and it give a great introduction to what DI is, how you should do it, patterns & antipatterns, and gives a great onramp for Unity and several other DI containers.