I am using the following in my controller
IAccountRepository AcctRep;
IAccountProductRepository AcctProdRep;
public HomeController(IUnityContainer container)
{
AcctRep = container.Resolve<IAccountRepository>();
AcctProdRep = container.Resolve<IAccountProductRepository>();
}
and in my UnityConfig.cs file in the AppStart..
container.RegisterTypes(AllClasses.FromLoadedAssemblies(),
WithMappings.FromMatchingInterface,
WithName.Default);
Why?
To Save myself from manually registering about 30 different repositories in UnityConfig.cs like below:
container.RegisterType< IAccountRepository, AccountRepository >();
To Save my Self the Hassle of doing the below in countless controllers
IAccountRepository AcctRep; IAccountProductRepository AcctProdRep; public HomeController(IAccountRepository acctRep, IAccountProductRepository acctProdRep) { AcctRep = acctRep; AcctProdRep = acctProdRep; }
and because what i proposed looks neater than above (imagine having to inject 4 Repositories)...
Question is am i having too much of a performance issue, or anything that I am not seeing and can regret in the future?
Edit A little part of this question is similar to the suggested duplicate but not entirely.. I.e. the using of Unity's AllClasses mappings and performance impact of doing the above vs the normal injection and issues I might face in the future if I go down that way.. @Konamiman's approach to the answer is very neat keeping question to see what others have to say..
I'd say that this is not a good idea because it hurts code maintainability. You are creating a strong coupling of your classes to the dependency injection engine, what if you decide in the future that you want to stop using Unity and (for example) switch to Autofac? It also hurts code readability, because it's not obvious what the class dependencies are.
So the proper way to go is either:
Pass the dependencies in the class constructor. It may seem a hassle at first, but it leads to more readable and maintainable code, and you should always favor code readability over your own write time convencience. Moreover, if you find yourself passing too much parameters in the constructor perhaps it's time to review your design (is your controller doing too much? Perhaps it should depend on a business class instead of directly depending on the four repositories...?)
At the very least, if you still want to pass the dependency resolver to your classes, create an abstraction of the dependency resolver so that you are isolated from the concrete engine used. Something like this should be good enough to start with:
.
You can then create and register an implementation of the class for Unity, which will be easily replaceable if ever needed.