I'm using WCF Facility with entity framework in ASP.NET application. The goal is to keep dbcontext in IoC container see example:
1)Global.asax
protected void Application_Start(object sender, EventArgs e)
{
Container = new WindsorContainer();
Container.AddFacility<WcfFacility>();
Container.Register(
Component.For<IDBContext>().ImplementedBy<DBContext>().LifeStyle.PerWcfOperation()
);
}
2)CustomerService.cs public class CustomerService : ICustomerService { private readonly ICustomerBl customerBl;
public CustomerService(ICustomerBl customerBl)
{
this.customerBl = customerBl;
}
public Customer GetById(int Id)
{
Customer customer = customerBl.GetById(5);
return customer;
}
}
3)CustomerBl.cs
public class CustomerBl : ICustomerBl
{
private ICustomerRepository _repository;
public CustomerBl(ICustomerRepository customerRepository)
{
_repository = customerRepository;
}
public Customer GetById(int Id)
{
return _repository.GetById(5);
}
}
4)CustomerRepository.cs
public class CustomerRepository: ICustomerRepository
{
public IDBContext _dbContext;
public CustomerRepository(IDBContext dbContext)
{
_dbContext = dbContext;
}
public Customer GetById(int Id)
{
_dbContext.ContextCounter = 1;
return new Customer
{
Id = 5,
FirstName = "Joe",
LastName = "Blogg",
Age = 45
};
}
}
5)TestServiceClient
protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.CustomerServiceClient customer = new ServiceReference1.CustomerServiceClient();
customer.GetById(5);
}
I'm doing following:
1)Call wcf method from CustomerGetById(), dbcontext is instantiated here _dbContext.ContextCounter = 0
2)Call again and has instantiated dbContext - _dbContext.ContextCounter = 1
The goal is to have new instance of dbContextafter each single wcf method call. How I can achieve this?
Thanks!
The following code will register component as PerWebRequest life style in WindsorContainer.
To make Life style as PerWebRequest you have to add following in Web.config