Armand
Armand

Reputation: 10264

IIS Web Application with database connection

I am working on a web application that is using Entity Framework, the SaveChanges method has been overriden to allow log entries of changes made to the database.

Now on MSDN it states that the database context is not thread safe. So I have 2 questions.

1) If I want to create the log entries in a thread do I have to use a new DB Context for each thread?

using (var repository = new LoggingRepository(new LoggingDbContext()))
{
    ((ILoggingRepository)repository).Persist(auditEntries);
}

Update: The logging database is a separate database from the one where the SaveChanges is overriden

2) Does the application create a new DB Context for each user that connects to the application through IIS?

Upvotes: 2

Views: 192

Answers (2)

oleksii
oleksii

Reputation: 35925

If I want to create the log entries in a thread do I have to use a new DB Context for each thread?

Yes you must use new context in each thread. This is not because of the logger, but because of the context itself. The loggers are usually thread-safe (depending on what you use), so you can pass the same instance of the logger to the different context.

Bear in mind, this is when you need to use thread id, as many threads will write to the same log output. There will be no order to the log entries. You can see a break in transaction in a log file, which doesn't indicate a problem, for example. It's just the way the log file was written to.

Does the application create a new DB Context for each user that connects to the application through IIS?

In most cases this is the correct approach. Moreover, not only you should construct new db context for each user, but also for each new request. DB Context uses connection pooling, which preserves physical connection and destroys logical connection when a managed connection object is disposed.

DB context was designed to be a lightweight object.

Upvotes: 1

Andy Hopper
Andy Hopper

Reputation: 3678

The example you provide would work. Every incoming request will be assigned to a thread from the thread pool, and your code would ensure that the lifetime of the DbContext is constrained to that thread.

Edit: If the logging table(s) are in the same database, you can simply add them to the model that your overridden SaveChanges() is on and use the current DbContext. I'm also assuming that you're using the original DbContext within either a using block or under an IDisposable-aware RequestLifetimeManager...

Upvotes: 1

Related Questions