WCF Custom OperationConext Lifetimemanager for EF DbContext

385 Views Asked by At
 container.RegisterType<IDataContextFactory<MyDataContext>, DefaultDataContextFactory<MyDataContext>>(new PerRequestLifetimeManager());

Created a PerRequestLifetimeManager using OperationContext but it does not seem call setValue function at all, it always trys to go to GetValue() function which always retruns null since nothing has been set.

My goal is to create a lifetimeManager for dbconetxt that will give me a new dbContext per method call. transient is not an option since it won;t work for join query.

 public class WcfOperationContext : IExtension<OperationContext>
    {
        private readonly IDictionary<string, object> items;

        private WcfOperationContext()
        {
            items = new Dictionary<string, object>();
        }

        public IDictionary<string, object> Items
        {
            get { return items; }
        }

        public static WcfOperationContext Current
        {
            get
            {
                WcfOperationContext context = OperationContext.Current.Extensions.Find<WcfOperationContext>();
                if (context == null)
                {
                    context = new WcfOperationContext();
                    OperationContext.Current.Extensions.Add(context);
                }
                return context;
            }
        }

        public void Attach(OperationContext owner) { }
        public void Detach(OperationContext owner) { }
    }

    public class PerRequestLifetimeManager : LifetimeManager
    {
        private string key;

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

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

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

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

There are 1 best solutions below

0
On BEST ANSWER

My solution for this was to use this nuget package: UnityWCF

The Service should be instantiated by Unity and new instance per call.

For this use this settings on the service:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ...

Inject DbContext where you need. And register in Unity like this:

container.RegisterType<DbContext, YourDbContext>(new HierarchicalLifetimeManager(), ...);