In the last few days, we are recording different exceptions thrown by entity framework (version 6) on our live stage, which only occur occasionally and show error messages, which all relate to the database connection.
Not allowed to change the 'ConnectionString' property. The
connection's current state is closed.
The context cannot be used while the model is being created. This
exception may be thrown if the context is used inside the
OnModelCreating method or if the same context instance is accessed by
multiple threads concurrently. Note that instance members of DbContext
and related classes are not guaranteed to be thread safe.
Unexpected connection state. When using a wrapping provider ensure
that the StateChange event is implemented on the wrapped DbConnection.
The underlying provider failed on Open.
We can not remember that we've changed anything and as already said these errors occur only sometimes. We can not reproduce them on local stage.
Does anyone have an idea what is going wrong or how to investigate?
Edit: It is an ASP.NET MVC 5 application which uses Unity IoC for instantiation. We use a self-written PerRequestLifeTimeManager which runs absolutely smooth in other mvc applications.
Thanks to the hint of #Gerd Arnold and #Chris Pratt I was able to figure out the root-cause of my issue.
Indeed the exceptions where caused by an instance of DbContext which was used concurrently accross multiple requests. This DbContext is part of an service which is injected by Unity property injection into an action filter. What I didn't know yet is that action filters don't get instantiated per request in APS.NET MVC but they are cached and reused. So do not inject instances of DbContext or DbContext-based classes into action filters!
We solved that issue by calling DependencyResolver.Current.GetService<ClassType>() instead of using Dependency-attribute in our filter's code to get an instance of the respective dependency (Please note that you lose the testability of the filter through this workaround)
It took me many hours to find the solution. To those users who occasionally encounter the same errors as mentioned in my question I would recommend check your appliation for any DbContext-based classes which might get used concurrently accross requests/threads.
Check your Unity IoC rules
Look for classes which do not get instantiated through IoC but might be used concurrently.
Check all steps along the MVC request lifecycle
Related
https://msdn.microsoft.com/en-us/library/microsoft.practices.unity.perrequestlifetimemanager(v=pandp.30).aspx states that:
Although the PerRequestLifetimeManager lifetime manager works correctly and can help in working with stateful or thread-unsafe dependencies within the scope of an HTTP request, it is generally not a good idea to use it when it can be avoided, as it can often lead to bad practices or hard to find bugs in the end-user's application code when used incorrectly. It is recommended that the dependencies you register are stateless and if there is a need to share common state between several objects during the lifetime of an HTTP request, then you can have a stateless service that explicitly stores and retrieves this state using the Items collection of the Current object.
What kind of bugs or bad practices is the warning refering to? How would one use it incorrectly? - Unfortunately the warning is not very specific and is therefore hard to apply to the real world. Furthermore it is not clear to me what stateful means in this context.
IMHO a typical scenario to use the PerRequestLifetimeManager would be some kind of database connection (e.g. DbContext) or similiar.
Its purpose would be to only instantiate one instance per request, which could (for example) prevent redundant operations and lookups during the course of a single request.
The danger is if someone assumes that the object created is a good place to store state during the request. The idea of dependency injection is that a class receives a dependency (commonly an interface) and doesn't "know" anything about it at all except that it implements that interface.
But someone could reason that if the object is going to persist throughout the life of the request then it's a good place to maintain state during the request. So they create a complex scenario where one class receives the dependency, stores some information in it (like setting a property), and then another class receives that same dependency and expects to read that property.
Now the purpose of dependency injection (decoupling) has been defeated because classes have built-in assumptions about what the lifetime of that dependency is, and may even include assumptions about what other classes have done or will do with the state of that object. That creates a tangled mess where the interaction between classes is difficult to perceive - even hidden - and so it's easy to break.
Let's say someone determines that the lifestyle of that dependency should be transient, not per web request. Suddenly all of the behaviors of those classes that depend on it stop working as expected. So developers look at those classes and see that nothing has changed. What happened? The interaction between those classes was hard to see in the first place, so when it breaks the problem will be hard to find. And if there was some valid reason why the lifestyle of that dependency was changed then the problem is going to be even harder to fix.
If we need to store state during a request then we should put it in "normal" places like in the HttpContext. There's still room there for some confusing practices and bugs, but at least we know that the HttpContext is (by definition) going to be tied to a particular request.
I have to work on already developed solution which is using NHibernate (v1.2.1.4000) with SQL Server 2008.
The application is using .NET Framework 2.0 due to Membership authentication and other stuffs.
This is working in Visual Studio - I can debug it, run in. But failed when deployed in IIS (v8.0)
Exception is:
Duplicate type name within an assembly.
HibernateException: Creating a proxy instance failed.
And it occurred whenever database is fetched to get some models.
I have googled on this issue and have some suggestion to use nhiberante (v3.3.x).
But the lots of interfaces and method parameters are different in v3. so it is breaking implementaion of the source code.
Several questions regarding this exist on stackoverflow but no luck yet
Maybe you have a concurrency trouble, something like singleton initialization failing to ensure uniqueness of its initialization, occurring only under load.
Especially check your session factory. Put logs when building it, check it is not built multiple times. Try triggering your singleton initializations from Application_Start if they are not already triggered from there.
Avoid singleton lazy initializations unless they are really heavy and not needed for most of you application HTTP requests. In such case, make sure their logic is thread safe and avoid running concurrent initializations (something like LazyThreadSafetyMode ExecutionAndPublication instead of PublicationOnly: it requires stricter locking but must be done that way for building the ISessionFactory, if it is done through lazy initialization.)
I see in many examples about MVC, Repository pattern, Unit of Work and EF, for instance here, that both interfaces and classes implement the IDisposable interface. I guess this interface exposes just the method Dispose() with 2 overloads.
However in many other examples made by senior programmers, I do not see such implementation. Actually to me it seems quite logic that one a component is dismissed on every web request, since every request gets a brand new controller instance.
Or even if this is not the case, I guess by using a dependency injection framework such as Ninject, we delegate all this disposal tasks to the very framework.
It can also be the case that the implementation of IDisposable was required in older version of the EF or MVC framework.
Anybody might point me to the right direction?
UPDATE
The automatic disposal of the context can be seen in a layered application with Service and Repository layer. Assume that from both components we return IQueryable<T> objects, if we try to populate the objects from the controller, by iterating its items or call the ToList() method, we get a runtime error saying that the context is unreachable (closed)
The common pattern is to have an instance of the Repository in every Controller and to link the Disposal into the Dispose() of the Controller.
So I would say the pattern is generally required.
However in many other examples made by senior programmers, I do not see such implementation.
There are a few possibilities:
it is Demo code, error and resource handling omitted.
the pattern is implemented in a non obvious place (base class)
Point to a concrete example and we can find out.
Usually in most of the examples you can find on interner about Repository pattern using EF the Context has a Dispose method.
Now you don't strictly need to call the Dispose method on the Context but it may be a good practice for the reason below:
DataContext holds state (for example, a SqlConnection and pointers to the objects you have retrieved). These will eventually get cleaned up by the GC once you release all references, but some of these objects (for example, the underlying SqlConnection) may be holding resources that you typically want to release as soon as your are finished, rather than relying on the GC to clean up.
For lazy people: you can even wrap the context within a using statement which will call the dispose for you when the object get out from the scope of the using itself
more info at :
http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/2625b105-2cff-45ad-ba29-abdd763f74fe/
here you can also find an example that regarding Repository patter in EF
http://www.codeproject.com/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C
With regards the connection state, EF is supposed to be quite good at only keeping the connection open only while it's needed (http://msdn.microsoft.com/en-us/library/bb896325.aspx). The link also shows how to get finer control over the connection state.
I'm not quite sure when I should use SingletonScope() vs TransientScope() vs RequestScope() when I do my binding in my global.cs file.
I have for example my call to MongoSession (using NoRM and the mvcStarter project http://mvcstarter.codeplex.com/) which is set to SingletonScope but I created a repository that use this MongoSession object to make calls to Mongo easier, e.g., I have a NewsRepository which uses MongoSession to fetch my News items from the data. As an example I have a call that fetches News items that has DisplayOnHome set to true and get the latest by CreationDate. Should such a repository be SingletonScope or would RequestScope would be more appropriate?
When should I use each of it and why?
In general in a web app, you want state to be request scope as much as possible.
Only in the case of very low level optimisations are you ever likely to run into a case where its appropriate to create singleton objects (and the chances even then are that you'll pull such caching / sharing logic out into another class which gets pulled in as a dependency on your other [request scope] objects and make that singleton scope). Remember that a singleton in the context of a web app means multiple threads using the same objects. This is rarely good news.
On the same basis, transient scope is the most straightforward default (and that's why Ninject 2 makes it so) - request scope should only come into the equation when something needs to be shared for performance reasons, etc. (or because that's simply the context of the sharing [as mentioned in the other answer]).
I guess the answer would depend on whether your MongoSession represents a unit of work or not. Most database related classes that I've worked with (mostly in the context of ORM, such as NHibernate or EF4) revolve around a context, entities, and tracked state that represent a unit of work. A unit of work should never be kept around longer than the length of time required to perform the given unit of work, after which the unit should be committed or rolled back. That would mean you should use RequestScope.
If your MongoSession is not a unit of work, you could keep it around for the lifetime of an MVC session, in which case SessionScope would then be appropriate.
From deleted question as requested by #shankbond above
The Disposal is not necessarily performed synchronously on your main request thread as one might assume.
You probably want to stash a Block and then Dispose() it at an appropriate phase in your request (how are you going to handle exceptions?)
Have a look in the Ninject Tests for more examples (seriously, go look - they're short and clear and I didnt regret it when I listened the 3rd time I was told to!)
See http://kohari.org/2009/03/06/cache-and-collect-lifecycle-management-in-ninject-20/
I am having this issue too, Lately, I started working on MongoDB. MongoDB recommends singleton for MongoClient. So I am still not sure about my implementation, and I am confused. I implemented the Mongo in the DI container two ways, and I am not sure which one is good. Let's take the first approach
Here I return a singleton instance of IMongoClient
services.AddSingleton(_ =>
{
return new MongoClient(con.ConnectionString);
});
Then,
services.AddScoped<IMongoDatabase>(s =>
{
var client = p.GetRequiredService<IMongoClient>();
return client.GetDatabase(con.DatabaseName);
});
Then, return a scoped for my IMongoDatabase. In my repo, I inject the IMongoDatabaseand then call my DB.
_dataContext = mongoDBClient.GetCollection<SomeCollection>(GetCollectionNameFromAppSetting((settings.DPUBotCollectionName)));
The second one I was returning an IMongoDatabase as a singleton:
services.AddSingleton<IMongoDatabase>(_ =>
{
//var connectionString = con;
return new
MongoClient(con.ConnectionString).GetDatabase("SomeDatabase");
});
Monog says their MonogClient and IMongoDatabase are thread-safe. I am not sure which approach is right. I would appreciate it if you could give me an answer.
First off, I wish context based storage was consistent across the framework!
With that said, I'm looking for an elegant solution to make these properties safe across ASP.NET, WCF and any other multithreaded .NET code. The properties are located in some low-level tracing helpers (these are exposed via methods if you're wondering why they're internal).
I'd rather not have a dependency on unneeded assemblies (like System.Web, etc). I don't want to require anyone using this code to configure anything. I just want it to work ;) That may be too tall of an order though...
Anyone have any tricks up their sleeves? (I've seen Spring's implementation)
internal static string CurrentInstance
{
get
{
return CallContext.LogicalGetData(currentInstanceSlotName) as string;
}
set
{
CallContext.LogicalSetData(currentInstanceSlotName, value);
}
}
internal static Stack<ActivityState> AmbientActivityId
{
get
{
Stack<ActivityState> stack = CallContext.LogicalGetData(ambientActivityStateSlotName) as Stack<ActivityState>;
if (stack == null)
{
stack = new Stack<ActivityState>();
CallContext.LogicalSetData(ambientActivityStateSlotName, stack);
}
return stack;
}
}
Update
By safe I do not mean synchronized. Background on the issue here
Here is a link to (at least part of) NHibernate's "context" implementation:
https://nhibernate.svn.sourceforge.net/svnroot/nhibernate/trunk/nhibernate/src/NHibernate/Context/
It is not clear to me exactly where or how this comes into play in the context of NHibernate. That is, if I wanted to store some values in "the context" would I get "the context" from NHibernate and add my values? I don't use NHibernate, so I don't really know.
I suppose that you could look and determine for yourself if this kind of implementation would be useful to you. Apparently the idea would be to inject the desired implementation, depending on the type of application (ASP.NET, WCF, etc). That probably implies some configuration (maybe minimal if one were to use MEF to load "the" ICurrentSessionContext interface).
At any rate, I found this idea interesting when I found it some time ago while searching for information on CallContext.SetData/GetData/LogicalSetData/LogicalGetData, Thread.SetData/GetData, [ThreadStatic], etc.
Also, based on your use of CallContext.LogicalSetData rather than CallContext.SetData, I assume that you want to take advantage of the fact that information associated with the logical thread will be propagated to child threads as opposed to just wanting a "thread safe" place to store info. So, if you were to set (pr Push) the AmbientActivity in your app's startup and then not push any more activities, any subsequent threads would also be part of that same activity since data stored via LogicalSetData is inherited by child threads.
If you have learned anything in the meantime since you first asked this question I would be very interested in hearing about it. Even if you haven't, I would be interested in learning about what you are doing with the context.
At the moment, I am working on maintaining some context information for logging/tracing (similar to Trace.CorrelationManager.ActivityId and Trace.CorrelationManager.LogicalOpertionStack and log4net/NLog context support). I would like to save some context (current app, current app instance, current activity (maybe nested)) for use in an app or WCF service AND I want to propagate it "automatically" across WCF service boundaries. This is to allow logging statements logged in a central repository to be correlated by client/activity/etc. We would be able to query and correlate for all logging statements by a specific instance of a specific application. The logging statements could have been generated on the client or in one or more WCF services.
The WCF propagation of ActivityId is not necessarily sufficient for us because we want to propagate (or we think we do) more than just the ActivityId. Also, we want to propagate this information from Silverlight clients to WCF services and Trace.CorrelationManager is not available in Silverlight (at least not in 4.0, maybe something like it will be available in the future).
Currently I am prototyping the propagation of our "context" information using IClientMessageInspector and IDispatchMessageInspector. It looks like it will probably work ok for us.
Regarding a dependency on System.Web, the NHibernate implementation does have a "ReflectiveHttpContext" that uses reflection to access the HttpContext so there would not be a project dependency on System.Web. Obviously, System.Web would have to be available where the app is deployed if HttpContext is configured to be used.
I don't know that using CallContext is the right move here if the desire is simply to provide thread-safe access to your properties. If that is the case, the lock statement is all you need.
However, you have to make sure you are applying it correctly.
With CallContext, you are going to get thread-safe access because you are going to have separate instances of CallContext when calls come in on different threads (or different stores, rather). However, that's very different from making access to a resource thread-safe.
If you want to share the same value across multiple threads, then the lock statement is the way to go. Otherwise, if you want specific values on a per-thread/call basis, use the CallContext, or use the static GetData/SetData methods on the Thread class, or the ThreadStatic attribute (or any number of thread-based storage mechanisms).