Reputation: 1341
Ok so I have looked at many posts on how to get DI working with web API. Trying to do simple ctor injection. What I am pasting here works but that doesn't mean I am happy with it. If anyone has some advice please sound off.
It appears we don't have to take control over controller creation in WEB API, which makes me question the proper releasing of dependencies. I have things setup as scoped, you will see by looking at the code. We are forced to use IDependencyResolver which I think sucks but this is the only workaround I can find as no other hooks that I have tried with IControllerActivator seem to work.
SEE CODE.
public class WindsorWeApiResolver:WindsorWebApiDependencyScope,IDependencyResolver
{
private readonly IWindsorContainer _container;
public WindsorWeApiResolver(IWindsorContainer container) : base(container)
{
_container = container;
}
public IDependencyScope BeginScope()
{
return new WindsorWebApiDependencyScope(_container);
}
}
public class WindsorWebApiDependencyScope:IDependencyScope
{
private readonly IWindsorContainer _container;
private readonly IDisposable _scope;
public WindsorWebApiDependencyScope(IWindsorContainer container)
{
_container = container;
_scope = _container.BeginScope();
}
public void Dispose()
{
_scope.Dispose();
}
public object GetService(Type serviceType)
{
return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType).Cast<object>().ToArray();
}
}
Upvotes: 1
Views: 506
Reputation: 46
I agree that IDependencyResolver is not ideal. I tried to negate the lack of release method, without fighting MVC, by using the Typed Factory Facility for the scope. See my post here. Your controllers can take constructor args as usual.
Upvotes: 1