Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor DI - Field is never assigned to, and will always have its default value

I have the following code:

private IMemoryCache _cache;

public HomeController(IMemoryCache memoryCache) : base() {    
   this._cache = memoryCache;    
}

ASP.Net Core is handling the injection of the IMemoryCache instance via:

public void ConfigureServices(IServiceCollection services) {
   services.AddMemoryCache();
}

It is flagging the _cache field with:

Field HomeController._cache is never assigned to, and will always have its default value null

It's not causing any errors, it is just distracting in the editor.

What is the way to go about convincing Visual Studio 2017 that I am in fact assigning this field a value, via the constructor?

Code (because the error overlaps it):

enter image description here

With the editor showing the error:

enter image description here

At runtime showing the valid instance being injected:

enter image description here

Edit:

For the comments suggesting to use:

private IMemoryCache _cache = null;

... this makes no difference, same exact result.

like image 510
Patrick Avatar asked Oct 30 '22 02:10

Patrick


2 Answers

Restarting Visual Studio 2017 and rebooting did not resolve the issue.

However, I was notified of Visual Studio 2017 update version 15.3.3 when the environment reloaded, which I installed.

After re-starting Visual Studio post-update, this situation is no longer occurring.

I doubt the update actually did anything related to this problem, it's more likely something in my VS configuration was off and the update put things back in place.

like image 127
Patrick Avatar answered Nov 15 '22 05:11

Patrick


I had the same case on VS2015. In my case Build -> Rebuild Solution resolved the issue.

like image 23
essential Avatar answered Nov 15 '22 06:11

essential