我在ASP.NET应用程序中使用WCF Facility和实体框架。 目标是将dbcontext保存在IoC容器中,请参阅示例:
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 公共类CustomerService:ICustomerService { 私人只读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);
}
我正在做以下事情:
1)从CustomerGetById()调用wcf方法,dbcontext在此处实例化 _dbContext.ContextCounter = 0
2)再次调用并实例化dbContext - _dbContext.ContextCounter = 1
目标是在每个单个wcf方法调用之后使用dbContexta的新实例。 我怎么能做到这一点?
谢谢!
答案 0 :(得分:0)
以下代码将在WindsorContainer中将组件注册为 PerWebRequest 生活方式。
public void Register(Component component)
{
WindsorContainer container = new WindsorContainer();
IKernel kernel = container.Kernel;
kernel.AddComponent(component.Name, component.Service, component.Impl,LifestyleType.PerWebRequest);
}
要将Life样式设置为PerWebRequest,您必须在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>
答案 1 :(得分:0)
尝试:
Container.Register(
Component.For<IDBContext>().ImplementedBy<DBContext>().LifeStyleTransient().AsWcfService()
);
适合我,但我无法弄清楚我如何告诉温莎使用我在服务中定义的服务行为