I managed to solve each request by declaring my custom class UnityResolver in the WebApiConfig class. The UnityResolver class uses the HttpConfiguration class, assuming you are using an OWIN context.
public static void Register(HttpConfiguration config) {
The ConfigureContainer class is just a class where I declare my IOC dependencies, as shown below:
private static void RegisterReleaseEnv(IUnityContainer container) {
It is very important that you use the HierarchicalLifetimeManager lifecycle manager to get a new instance for each request.
The UnityResolver class is as follows:
public class UnityResolver : IDependencyResolver { protected IUnityContainer container; public UnityResolver(IUnityContainer container) { if (container == null) { throw new ArgumentNullException("container"); } this.container = container; } public object GetService(Type serviceType) { try { return container.Resolve(serviceType); } catch (ResolutionFailedException) { return null; } } public IEnumerable<object> GetServices(Type serviceType) { try { return container.ResolveAll(serviceType); } catch (ResolutionFailedException) { return new List<object>(); } } public IDependencyScope BeginScope() { var child = container.CreateChildContainer(); return new UnityResolver(child); } public void Dispose() { container.Dispose(); } }
Hope this helps.
For more information: http://www.asp.net/web-api/overview/advanced/dependency-injection
Shaun grech
source share