Dispose DBContext when request completes when using MEF for dependency injection - asp.net-web-api

I am currently working on a Web API project that uses MEF for dependency injection.
In other projects I have used Unity and its PerRequestLifetimeManager to dispose the DBContext when the request completes.
However, I could not find a way to perform the same task with MEF.
So my question is - how can I dispose the DBContext when the request completes when using MEF for dependency injection?

Related

AWS Lambda C# EF Core Serialization Error

I created a .net 6 minimal API project with EF Core that uses DI to create repositories with Scoped lifetime. The API project uses mediatr to send the request to a proper handler. The handler's get injected with db repositories. This works when I run this project directly.
I am migrating that project to an AWS Lambda project using the new AWS .NET 6 Templates in the visual studio toolkit. For whatever reason, the exact same code that runs fine in the minimal API project now throws an error because the injected repositories dispose their connections before the end of the request.
This error occurs anytime I run a command against the database.
I believe this is happening because of a serialization error that occurs in entity framework core. This issue doesn't occur in my regular project because I'm guessing it's using a different serializer to handle the serialization of entities.
The errors being thrown are:
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles.
Cannot access a disposed context instance
If I update the Json Serializer that .net is using to handle cycles, then the 1st error turns into: "System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported".
This looks like some sort of conflict with Pomelo Entity Framework Core
and the way the .net 6 lambda templated project is setup.
EDIT:
After looking at this more, I think the issue is with whatever serialization library that AWS Lambda template project uses vs whatever serialization library is normally used by Pomelo to handle things.

Asp Web Api Lifecycle issue

Im using web api 2
I have an authentication filter (implementing IAuthenticationFilter) that checks a token and sets a ClaimsPrinciple on both the Thread and the HttpContext. One such claim is the userId
I am using Windsor for Dependency Injection using the method described here.
http://blog.ploeh.dk/2012/10/03/DependencyInjectioninASP.NETWebAPIwithCastleWindsor/
This will create the object graph for my controllers and therefore new up any dependencies that the controllers have
The problem is that one of the constructors in one of the dependency's makes a call that requires the userid
And it seems that this (the constructor call) occurs before it has been set by the authentication filter
What are my options here?
When Web API needs a controller, the dependency injection is used to create it. This always happens before executing the pipeline. So you cannot access to the userid which is set later.
There are at least these solutions.
resolve the dependency when needed (i.e. use the DI container as service locator). I don't like this one
lazy initialize the dependency (I don't know if Castle Windsor can do it, but it looks like it's possible: Lazy Loading using Windsor Castle) Not so bad
change the implementacion of that component, and receive the userid as parameter, where needed, so that it's available when you want to use it. I prefer this one

Is it mandatory for DbContext to be injected .InPerRequestScope in ASP.NET application?

I have been using Ninject IoC container in my ASP.NET MVC3 portal. Whenever I've been injecting Entity Framework DbContext in PerThread scope, my data wasn't consistent, changes would not get displayd for some time after I've made changes to Entities, etc.
After I've switched the IoC configuration to resolve a fresh copy of my DbContext instance for each request (PerRequestScope()), all the problems were gone.
So is it absolutely mandatory to use PerRequest injection strategy in MVC3 applications?
Yes, it is mandatory.
Your problem works like this:
Thread A loads an entity
Thread B modifies that entity
The next request to Thread A uses the cached entity from the first request, ignoring the changes

Entity Framework (EF) Model First Approach + Ms Unity dependency injection container

thanks in advance for your support. I would like to receive guidance in order to implement Ms Unity dependency injection container with EF Model First approach by using edmx files in an asp.net MVC project.
At this moment I found many projects using EF Code First + unity but I was not able to find a project implementing data model edmx files with Unity DI.
brgds!.
The decision to use Model First development shouldn't affect how you would use Dependency Injection, whether with Unity or any other container. The objects generated from the edmx file aren't ones that you would be injecting. You will still need to code your own abstractions - things like IRepository or IUnitOfWork - and those would be dependencies that you inject.
See, for example, this similar question and its answer.

Using Unity and a custom LifetimemManger for Unit Of Work / Repositories / Services on an MVC3 application?

I am using unity 2.0 with MVC3 and need some help understanding the LifeTimeManagers. I have read a lot of people using a custom LifeTimeManager that places items into the HTTPContext. This makes perfect sense because you only want the UoW around for the lifetime of the request in MVC. However, do I need the same lifetime manager for my repositories and services? I was looking at this post and noticed the same lifetime manager for the UoW, repositories, and services.
My Repositories depend on a UoW, and my Services depend on the Repositories. I am not sure what Unity does, by default, regarding a lifetime manager, but I did create a custom HttpContext manager and have had issues with it just being on the UoW. I have not put it on any of my services or repositories yet. I am wondering if I need to or if that is the best practice.
Simply use the Nuget package for unity.mvc3 and it contains a hierarchicallifetimemanager. When you register the types that need to be disposed in your mappings, it will dispose them.
DOn't worry about doing anything directly with httpcontext, this is far easier.
See the section on
IDisposable dependencies
http://www.devtrends.co.uk/blog/integrating-the-unity.mvc3-1.1-nuget-package-from-scratch
For anything you want disposed explicitly (that implements IDisposable) use this lifetime manager:
container.RegisterType(new HierarchicalLifetimeManager());

Resources