views:

36

answers:

1

Hi. I am using Dependency Injection pattern to resolve correct instance of mine UnitOfWork. When I am using only one type mapping, all is ok

unityContainer.RegisterType<IUnitOfWork, UnitOfWork>(); 

The problem occurs when I am using two type mappings for the same interface:

unityContainer.RegisterType<IUnitOfWork, UnitOfWork1>(); 
unityContainer.RegisterType<IUnitOfWork, UnitOfWork2>(); 

I have very common code that making a call like

var unitOfWork = ServiceLocator.GetInstance<IUnitOfWork>(); 

In some cases it should return UnitOfWork, in some cases it should return UnitOfWork2.

How I resolve this problem without refactoring of common part?

P.S. And yes - I Know about named containers ))

A: 

You could use named instances instead of named containers. You can register a named instance with Unity like this:

unityContainer.RegisterType<IUnitOfWork, UnitOfWork1>("MyUnit1");
unityContainer.RegisterType<IUnitOfWork, UnitOfWork2>("MyUnit2");

Then, to resolve the correct instance, you can use the following syntax:

var unitOfWork = ServiceLocator.GetInstance<IUnitOfWork>("MyUnit2"); 

Another option is to decorate your another UnitOfWork-class with some interface (for example IUnitOfWork2). Then register UnitOfWork2 to IUnitOfWork2 and resolve the instance by that new interface when needed.

Though you mention that you don't want to refactor the ServiceLocator.GetInstance-method. I still think that the easiest way would be to add an optional parameter to the GetInstance-method and use the named instances. If that is out of question, you could perhaps register a factory-class to IUnitOfWork and use that to get the correct UnitOfWork-implementation. Here's a short guide on how to register a factory with Unity. Please note that latest version of Unity may have a different way of doing this. Also, here's a question from Stack Overflow which deals with Unity containers and factories.

Mikael Koskinen
Thanks for your advise. But the problem is more comlicated then it seems.
Brian J. Hakim
Could you expand on your problem? Maybe we can find an another solution.
Mikael Koskinen