适用于WCF的Castle Windsor LifeStyle

本文关键字:Windsor LifeStyle Castle WCF 适用于 | 更新日期: 2023-09-27 18:19:43

我在ASP.NET应用程序中使用带有实体框架的WCF功能。目标是将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) 客户服务.cs公共类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) 客户Bl.cs

public class CustomerBl : ICustomerBl
{
    private ICustomerRepository _repository;
    public CustomerBl(ICustomerRepository customerRepository)
    {
        _repository = customerRepository;
    }
    public Customer GetById(int Id)
    {
        return _repository.GetById(5);
    }
}

4) 客户存储库.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) 测试服务客户端

    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。Context计数器=1

目标是在每个wcf方法调用之后都有一个新的dbContext实例。我怎样才能做到这一点?

谢谢!

适用于WCF的Castle Windsor LifeStyle

以下代码将组件注册为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);                                 
     }

要使生活方式成为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>

尝试:

 Container.Register(
        Component.For<IDBContext>().ImplementedBy<DBContext>().LifeStyleTransient().AsWcfService()
        );

对我有用,但我不知道如何告诉Windsor使用我在服务中定义的Servicebehavior