This code can be used to keep a ObjectContext live during a WCF Service OperationContext.
The following code can be used within a WCF Service to share a ObjectContext between other objects, for example between Repositories so they can reuse the same Unity of Work and Identity Map during a WCF Operation.
public interface IObjectContext : IDisposable
{
IObjectSet<T> CreateObjectSet<T>() where T : class;
void SaveChanges();
}
public class WcfObjectContextAdapter : IObjectContext
{
public IObjectSet<T> CreateObjectSet<T>() where T : class
{
return Context.CreateObjectSet<T>();
}
public void SaveChanges()
{
Context.SaveChanges();
}
public void Dispose()
{
Context.Dispose();
}
public WcfObjectContextAdapter(IObjectContextFactory objectContextFactory)
{
if (objectContextFactory == null)
throw new ArgumentNullException("sessionFactory");
if (Context == null)
Context = objectContextFactory.Create();
}
public ObjectContext Context
{
get
{
if (WcfOperationContainerExtension.Current == null)
return null;
return WcfOperationContainerExtension.Current.Context;
}
set
{
if (CurrentOperationContext == null)
return;
CurrentOperationContext.Extensions.Add(new WcfOperationContainerExtension(value));
CurrentOperationContext.OperationCompleted += CurrentOperationContext_OperationCompleted;
}
}
private void CurrentOperationContext_OperationCompleted(object sender, EventArgs e)
{
var context = WcfOperationContainerExtension.Current.Context;
context.Dispose();
}
private OperationContext CurrentOperationContext
{
get { return OperationContext.Current; }
}
private class WcfOperationContainerExtension : IExtension<OperationContext>
{
public ObjectContext Context { get; set; }
public WcfOperationContainerExtension(ObjectContext context)
{
Context = context;
}
public void Attach(OperationContext owner) { }
public void Detach(OperationContext owner) { }
public static WcfOperationContainerExtension Current
{
get
{
if (OperationContext.Current == null)
return null;
return OperationContext.Current.Extensions.Find<WcfOperationContainerExtension>();
}
}
}
}
Can be used together with the
BaseRepository
Fork
Keep Entity Framework ObjectContext in a WCF Service OperationContext - @fredrikn Wednesday 14, 2010 7:49 AM
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


1.36k
0




Mark 'c#' tag as 'like'
Mark 'c#' tag as 'ignore'