开发者

Entity framework DbContext in wcf per call instance mode

I have a repository like this

public abstract class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected DbContext _dbContext;

    public BaseRepository(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public TEntity GetByKey(object keyValue)
   开发者_如何学编程 {
        // todo
    }
}

and a concrete repository like this

public CustomerRepository : BaseRepository<Customer> , ICustomerRepository
{
     public CustomerRepository(DbContext context) : base (context) { }

     public Customer FindCustomerByKey(string key)
     {
          _dbContext.Set<Customer>().Find(key);
     }

}

I have wcf service like this

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class CustomerSatisfactionService : ICustomerSatisfactionService
{
    private ICustomerRepository _customerRepository;
    private IHelpDeskRepository _helpdeskRepository;


    public AccountService(ICustomerRepository customerRepository,IHelpdeskRepository  helpdeskRepository)
    {
        _customerRepository = customerRepository;
        _helpdeskRepository = helpdeskRepository;
    }

    public void DoSomethingUsingBothRepositories()
    {
         //   start unit of work
         // _customerRepository.DoSomething();
         // _helpdeskRepository.DoSomething();
         // commit unit of work
    }


 }

and I am using StructureMap for injecting DbContext instances like this

For<DbContext>().Use(() => new MyApplicationContext());

My problem is when a client calls the service, a new CustomerSatisfactionService instance is created, hence new instances of CustomerRepository and HelpdeskRepository are created but with different DbContexts.

I want to implement the unit of work pattern, but in the DoSomethingWithBothRepositories method, the two repositories have different DbContexts.

Is there any way to tell structure map to spin up a DbContext instance on a per call basis?


You must specify lifecycle for your DbContext so that only one instance is created per call. StructureMap doesn't contain build-in lifecycle management for per call WCF but you can find one implementation on this blog.


You need to implement UnitOfWork pattern so that same context is shared amongst entities. Take a look at http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx for a way to implement it.


I don't know if you need/want StructureMap to control the instantiation of dbcontext, have a look at this reply, UoW and UoW Factory setup dbcontext for the calls that need to be made in the repository.

EF ObjectContext, Service and Repository - Managing context lifetime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜