I create SPA application. So there are mvccontrollers and webApicontrollers.
I install Unity using Package Manager and register my services using Unity.
When i test it on MvcController - everything works. But when i start test it on WebApiController - i get error. After some research i found answer here : http://www.asp.net/web-api/overview/advanced/dependency-injection
But now i have question-problem : where i should register my services - in UnityConfig file or in WebAPIConfig file or in both?
Registering of types in WebApiConfig :
var container = new UnityContainer();
container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
Registering of types in UnityConfig:
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
}
答案 0 :(得分:0)
You should only create one single Unity container, this way, you will have to register your services in one single place.
I would suggest registering everything in UnityConfig, and then changing WebApiConfig to use the existing container instead of creating a new one.
Replace the 3 lines you you mention in your question by this single line :
config.DependencyResolver = new UnityResolver(UnityConfig.GetConfiguredContainer());