Unity async/await for WCF app, what is the right lifetime manager for dbContext

341 Views Asked by At

I am using a Unit of Work pattern with EF using this library https://github.com/ziyasal/RepositoryT.EntityFramework

When using hierarchical lifetime manager for dbContext I get the error shown below when doing load test. If I use transientLifeTimeManager, the load test passes but I cannot do joins between tables. For table joins I get the specified LINQ expression contains references to queries that are associated with different contexts.

I am using await on all of my queries

container.RegisterType<IDataContextFactory<MyDataContext>, DefaultDataContextFactory<MyDataContext>>(new HierarchicalLifetimeManager());

Error due to Hierarchical

A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

When I am doing join with something like this, it errors out with

from appLocale in _applicationLocalesRepository.GetAll()
                      join app in _applicationsRepository.GetAll()
                      on appLocale.ApplicationID equals app.ApplicationID
                      select appLocale).ToList()).Select(x => x.Locale)

I have also tried to use this but did not work

 public class PerRequestLifetimeManager : LifetimeManager
 {
        private Guid key;

        public PerRequestLifetimeManager()
        {
            key = Guid.NewGuid();
        }

        public override object GetValue()
        {
            if (HttpContext.Current == null)
            {
                return null;
            }
            else
            {
                return HttpContext.Current.Items[key];
            }
        }

        public override void RemoveValue()
        {
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Items.Remove(key);
            }
        }

        public override void SetValue(object newValue)
        {
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Items.Add(key, newValue);
            }
        }
    }
0

There are 0 best solutions below