issues and solutions Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/category/c-sharp/issues-and-solutions/ Everyone can code! Sun, 18 Oct 2020 00:30:48 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.2 209870635 How to resolve Cannot access a disposed object in Dotnet Core when injecting DbContext https://blogs.learnsmartcoding.com/2020/10/18/how-to-resolve-cannot-access-a-disposed-object-in-dotnet-core-when-injecting-dbcontext/ https://blogs.learnsmartcoding.com/2020/10/18/how-to-resolve-cannot-access-a-disposed-object-in-dotnet-core-when-injecting-dbcontext/#respond Sun, 18 Oct 2020 00:30:48 +0000 https://karthiktechblog.com/?p=725 Accessing DbContext after it is disposed will cause a “Cannot access a disposed object in dotnet Core when injecting DbContext” error. Entity Framework (EF) Core is a lightweight, open-source. EF Core can serve as an object-relational mapper (O/RM). A DbContext instance represents a session with the database and can be used to query and save […]

The post How to resolve Cannot access a disposed object in Dotnet Core when injecting DbContext appeared first on Learn Smart Coding.

]]>
Accessing DbContext after it is disposed will cause a “Cannot access a disposed object in dotnet Core when injecting DbContext” error.

Entity Framework (EF) Core is a lightweight, open-source. EF Core can serve as an object-relational mapper (O/RM). A DbContext instance represents a session with the database and can be used to query and save instances of your entities.

DbContext is a combination of the Unit Of Work and Repository patterns and it is not thread-safe.

DbContext should not be accessed by multiple threads at the same time. In the dot net core, there are different possibilities of getting this error.

Possibility of getting Cannot access a disposed object error

When DbContext is used by multiple threads, one thread opens the connection to execute the query, and meanwhile, the second thread might have executed its query and closes the connection.

When this happens, the first thread throws an error that the DbContext is disposed. Avoid using multithreading with DbContext. Read more on working with DbContext

In dot net core, we have three service lifetime. Most of the time, DbContext is configured to be scoped service.

  • Transient
  • Scoped
  • Singleton

When an http request is served and returned with response, if you access DbContext service instance in any of the background work, then you will get this error.

Refer to this post for more details on how to Implement background tasks using IHostedService and access scoped service using IServiceScopeFactory

How to access scoped service using IServiceScopeFactory

Inject IServiceScopeFactory in the constructor and using this service you can get scoped service as described below.

        private readonly ILogger<StatusCheckerService> logger; 
	private readonly IServiceScopeFactory serviceScopeFactory;

        public StatusCheckerService(
            ILogger<StatusCheckerService> logger,IServiceScopeFactory serviceScopeFactory)
        {          
            this.logger = logger;
            this.serviceScopeFactory = serviceScopeFactory;
        } 

//In the method where you need scoped service, use below.

using (var scope = serviceScopeFactory.CreateScope())
                {
	// You can ask for any service here and DI will resolve it and give you back service instance
var contextService = scope.ServiceProvider.GetRequiredService<IContextService&ht;(); 
				   contextService.YourMethodOrServiceMethod(); //access dbcontext or anything thats available form your service
	}

Related Posts

Conclusion

In this post, I showed how to avoid Cannot access a disposed object in dotnet Core when injecting DbContext error. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below

The post How to resolve Cannot access a disposed object in Dotnet Core when injecting DbContext appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/10/18/how-to-resolve-cannot-access-a-disposed-object-in-dotnet-core-when-injecting-dbcontext/feed/ 0 725
This project references NuGet package(s) that are missing on this computer. https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/ https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/#respond Thu, 16 Apr 2020 02:49:09 +0000 https://karthiktechblog.com/?p=463 Many of us have ran into issue “This project references NuGet package(s) that are missing on this computer”. There are many different reason as to why someone will get this error while you build the solution. Error Details This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download […]

The post This project references NuGet package(s) that are missing on this computer. appeared first on Learn Smart Coding.

]]>
Many of us have ran into issue “This project references NuGet package(s) that are missing on this computer”. There are many different reason as to why someone will get this error while you build the solution.

Error Details

This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props

Looking at the error, it is triggered from somewhere in the code. Let’s go to the .csproj file and this can be found at the end of the file.

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
  </Target>

A solution to “This project references NuGet package that are missing error”

The error is tied to the package Microsoft.CodeDom.Providers.DotNetCompilerPlatform. Follow the below three steps to solve the issue.

Step 1

Remove the package from package.config file.

<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net46" />

Step 2

Edit the .csproj project file and removed the below settings

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
  </Target>

Step 3

Go to package manager console and run the command Update-Package –reinstall

Step # 2 and 3 were given by other users and I appreciate those users. Point # 1, removing the Microsoft.CodeDom.Providers.DotNetCompilerPlatform from package.config file is more important. Also, after running the command mentioned in step #3, the issue resolved. All unwanted packages removed and required package reference updated

Reference

There are other similar fixes which might work for few scenarios. Take a look at this post from StackOverflow

Also Read

How to upload a file in ASP.NET Web API

Conclusion

In this post, I showed how to resolve a common error “This project references NuGet package(s) that are missing on this computer”. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post This project references NuGet package(s) that are missing on this computer. appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/feed/ 0 463