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.)