I'm using Umbraco which has a lot of custom web API controllers under the hood. I would like to ignore them in simple injector and just manually register my own web api controllers.
Should I register the controller's lifestyle as transient or scoped? Web api controllers implements IDisposable
, but if I understand it correctly, simple injector registers them as transient when using container.RegisterMvcControllers()
. If they should be transient when using web api too? If so, I suppose I have to suppress the disposable warning?
How would the registration look like? If I simply do a container.Register<MyController>(Lifestyle.Transient)
and my controller injects another registered interface, i.e. public MyController(IMyRegisteredInterface foo)
, it will throw the exception Make sure that the controller has a parameterless public constructor
.
I would like to ignore them in simple injector and just manually register my own web api controllers
You can easily ignore them, while still enjoying batch-registration by supplying only the assemblies you wish to be scanned to the RegisterWebApiControllers
method as follows:
container.RegisterWebApiControllers(httpConfiguration,
typeof(MyApiController).Assembly);
Should I register the controller's lifestyle as transient or scoped?
You can do both, but registering them as transient is typically the easiest because that prevents that all its dependencies should be Scoped as well. Downside of this is that, since ApiController
implements IDisposable
, it means that you will have to suppress the DisposableTransientComponent
diagnostic warnings. This is actually a design flaw in Web API, because base classes and interfaces should typically not implement IDisposable
. This warning can be suppressed, because Web API will ensure disposal.
Simplest thing to do is to use the batch-registration facility supplied by the RegisterWebApiControllers
method, because it will suppress this warning for you automatically.
Make sure that the controller has a parameterless public constructor.
Make sure you follow the Web API Integration Guide, and especially use the SimpleInjectorWebApiDependencyResolver
; it will ensure that Controllers are resolved by Simple Injector.