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!
Try:
Container.Register(
Component.For<IDBContext>().ImplementedBy<DBContext>().LifeStyleTransient().AsWcfService()
);
Works for me, but I cant figure out how I tell Windsor to use the Servicebehavior I defined in the Service
The following code will register component as PerWebRequest life style in WindsorContainer.
public void Register(Component component)
{
WindsorContainer container = new WindsorContainer();
IKernel kernel = container.Kernel;
kernel.AddComponent(component.Name, component.Service, component.Impl,LifestyleType.PerWebRequest);
}
To make Life style as PerWebRequest you have to add following in Web.config
<system.web>
<httpModules>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.MicroKernel" />
</modules>
</system.webServer>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.