1

I got ASP.NET MVC application and I'm using EF code first and Unity dependency injector. I've implemented the DDD design and have repositories and services which interact with my POCO objects.

My problem is that I'm getting EF related problems - such as the connection was closed, the entities changed or not tracked and so on. As I've understand from researches in Google, it related to the way that I should configure Unity.

I've understood that I need to put it as per request instance, but as I see there's no built-in strategy in Unity nor in the Unity.Mvc3 package. I've tried to write my own strategy, which solved many problems but I do stuck with the problem that sometimes I get "connection closed".

My HttpContextLifetimeManager.cs

public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
    public override object GetValue()
    {
        return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
    }

    public override void RemoveValue()
    {
        HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
    }

    public override void SetValue(object newValue)
    {
        HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
    }

    public void Dispose()
    {
        RemoveValue();
    }
}

And inside DependencyConfig.cs (MVC 4 App_Start) I'm registering it using:

container.RegisterInstance<MyDbContext>(new MyDbContext(), new HttpContextLifetimeManager<DependencyConfig>());

Can you recommend me an implementation that works/help me fix mine/forward me to an article or a tutorial that can help me solve that problem?

Thanks a lot.

1 Answer 1

1

App_Start method is only called once when the first request comes for the application.

    Called when the first resource (such as a page) in an ASP.NET application is requested.  
 The Application_Start method is called only one time during the life cycle of an application.  

See MSDN

Therefore you are creating the one context for all requests. Then after sometimes it may be disposed. And it's not a good practice to keep one DbContext for all the requests (memory issues etc..).
So you can try putting that code in the Application_BeginRequest .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.