Entity framework DbContext in wcf for call instance mode

I have such a repository

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 specific 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 a 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 use StructureMap to input DbContext instances like

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

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

I want to implement a working template unit, but in the DoSomethingWithBothRepositories method, the two repositories have different DbContexts.

Is there a way to tell the structural map to deploy an instance of DbContext for each call?

+4
source share
3 answers

You must specify a life cycle for your DbContext in order to create only one instance for each call. StructureMap does not contain built-in lifecycle management for each WCF call, but you can find one implementation on this blog .

+4
source

You need to implement the UnitOfWork template so that the same context is shared between entities. See http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx for the method its implementation.

0
source

I don't know if you need / need a StructureMap to control dbcontext creation, look at this answer from UoW and UoW Factory setup dbcontext for calls that need to be made in the repository.

EF ObjectContext, Service and Repository - Manage the context lifetime.

0
source

Source: https://habr.com/ru/post/1339694/


All Articles