Simple injector handling warnings for api web controllers

I follow the docs docs website docs.

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 am not sure how to set the scope for the controllers, since the container.RegisterWebApiControllers(config) method is part of the webapi package and has no overloads. How to set them for each web request? Elsewhere, I would do this container.Register<IPinger, Pinger>(lifestyle); but it looks like I should use a batch helper method


Add this line to filter unwanted false negatives

 results = results.Where(x => !(x.ServiceType.BaseType == typeof (ApiController) && x.Description.Contains("IDisposable")) ).ToArray(); 
+6
source share
1 answer

The Disposable Transition Components page provides additional information about this warning and reports:

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

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

Although the lifestyle of Web API controllers can be safely extended to a per-web-api request, it’s generally better to leave your root objects transient. Lifestyle promotion would force you to encourage the lifestyle of these addictions, and also make every sign-up in the app at least for a web request. Although it can be done safely without any problems, it can make your registration a little more complicated and can affect the speed with which large graphs of objects are allowed.

So the warning is false in your case. It can be safely ignored. It would be nice if the integration libraries suppressed 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))); 
+4
source

Source: https://habr.com/ru/post/982560/


All Articles