Using Unity in a Web API project, I have registered an object (type MyService
implementing IMyService
) in a UnityContainer the standard way.
public static class UnityConfig {
public static void RegisterComponents() {
var container = new UnityContainer();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
// Register my type
container.RegisterType<IMyService, MyService>();
}
}
I resolve the object in one of my classes like this (it's not a controller so I can't use constructor injection):
// Get object from container
var myService = (IMyService)GlobalConfiguration.Configuration.DependencyResolver
.GetService(typeof(IMyService));
Is that the correct way? It seems so clunky. Is there a more succinct way to make this call, such as accessing the container's Resolve<T>()
method directly?
(I may be splitting hairs here but I'm new to using Unity with Web API and trying to understand the best practices.)
"Is that the right way"?
Generally speaking if you are using proper DI principals the answer is No. What you doing is asking the DependencyResolver to resolve the service IMyService. This is also known as Hollywood Principal: don't call the container; it'will call you.
This is also no different to asking the Unity Container to resolve the IMyService. i.e Container.Resolve
The best approach is to use proper Constructor Injection, if not property Injection or some of the designated injection patterns https://github.com/ninject/Ninject/wiki/Injection-Patterns
If your DEPENDENCY requires injecting more than often in many classes you may also consider using an Ambient Container. But this is unlikely the case. What is the meaning of the word ambient in this comment from CommonServiceLocator?
Also notice that your class that consumes the DependencyResolver is using DI technique i.e .Resolve which is not visiable by the out side of the class. This also means the component cannot be reuse as the outside world would not know for sure what DI it requires at compile time. If the DI requires is not registered then can cause runtime error (if the DEPENDENCY has not been registered).