I have a method which constructs dependencies using Unity. Currently, all of the calls do pretty much the same thing: Registers 2 repository object and 2 'App Part' objects. My issue is, there's a lot of them and the method has become massive. I've generalised the calls but here's an example:

container.RegisterType<IRepositoryOneDataAccess, RepositoryOneDataAccess>();
container.RegisterType<IRepositoryTwoDataAccess, RepositoryTwoDataAccess>();
container.RegisterType<IAppPart, FirstAppPart>("FirstAppPart.TestName");
container.RegisterType<IAppPart, SecondAppPart>("SecondAppPart.TestName");

I though that this could be split out to reduce the code in the method which registers the types with the container.

Firstly I moved the bottom 2 calls to another method since they both register to the same interface, I came up with this method:

private void RegisterParts<TPartOne, TPartTwo>(string firstAppPartName, string secondAppPartName) where TPartOne : IAppPart where TPartTwo : IAppPart
    container.RegisterType<IAppPart, TPartOne>(firstAppPartName);
    container.RegisterType<IAppPart, TPartTwo>(secondAppPartName);

This seems to work but I'm not sure this is the best way to do it. I would also like to move the other calls out into another method preferably the same as this one I've created but I'm not sure how to do it or even if it's possible.

Is there a better way of refactoring this?

  • Are the "One" and "Two" in your IRepository type names somehow related to the "First" and "Second" IAppParts ? At first sight those names sound really odd - it's hard to help not knowing exactly what they are supposed to do though. Commented Jun 19, 2013 at 11:57
  • No they aren't. They're not really what mine are called I just tried to keep the names basic so anyone could relate to them
    – Serberuss
    Commented Jun 19, 2013 at 14:51

1 Answer 1


This can be done using reflection over the assemblies if you use some conventions. Other DI libraries like StructureMap which I use has this feature. A quick search for Unity found this library Unityconfiguration although I haven't used it.

I also see that Unity 3.0 supports registration by convention. So the easiest option may be to upgrade.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.