Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple injector lifestyle warnings for web api controllers

I'm following the docs on the simple injector docs site.

https://simpleinjector.readthedocs.org/en/latest/diagnostics.html

var container = new Container();
container.RegisterWebApiControllers(config);
container.Verify();

var results = Analyzer.Analyze(container);

results.Should()
  .HaveCount(0, String.Join( Environment.NewLine, results.Select(x => x.Description)));

However when I run my test I get the following error

Xunit.Sdk.AssertException: 
Expected collection to contain 0 item(s) because 
MyController is registered as transient, but implements IDisposable., 
but found 1.

I'm not sure how to set the scope for controllers as the method container.RegisterWebApiControllers(config) is part of the webapi package and doesn't have any overloads. How do I set these to per web request? Elsewhere I would do this container.Register<IPinger, Pinger>(lifestyle); but it seems like I should be using the packaged helper method


Add this line in to filter out the unwanted false negatives

results = results.Where(x => 
   !(x.ServiceType.BaseType == typeof (ApiController) && 
     x.Description.Contains("IDisposable"))
    ).ToArray();
like image 469
Neil Avatar asked Feb 16 '15 13:02

Neil


1 Answers

The Disposable Transient Components page contains more information about this warning and states:

This warning can safely be ignored when: Dispose is called by the application code

In the case of Web API, the Web API framework registers controllers for disposal, so this warning can safely be ignored for Web API controllers.

Although the lifestyle of Web API controllers can safely be increased to per-web-api-request, in general it is better to leave your root objects transient. Promoting the lifestyle will force you to promote the lifestyle of those dependencies as well, and will cause every registration in the application to be at least per-web-request. Although this can be done safely without any problem, this can make your registration a bit more complicated, and can have impact on the speed in which large object graphs are resolved.

So the warning is a false-positive in your case. It can safely be ignored. It would be good if the integration libraries suppress these warnings. I just created a work item for this. Expect it to be fixed in a future release.

You can use the following code to suppress these warnings:

var results = 
    from result in Analyzer.Analyze(container)
    let disposableController =
        result is DisposableTransientComponentDiagnosticResult &&
        typeof(ApiController).IsAssignableFrom(result.ServiceType)
    where !disposableController
    select result;

results.Should().HaveCount(0, String.Join(Environment.NewLine,
    results.Select(x => x.Description)));
like image 107
Steven Avatar answered Nov 03 '22 22:11

Steven