Castle Windsor LifeStyle для WCF?

Я использую WCF Facility с структурой сущностей в приложении ASP.NET. Цель состоит в том, чтобы сохранить 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) Вызовите метод wcf из CustomerGetById (), здесь создается экземпляр dbcontext _dbContext.ContextCounter = 0

2) Вызовите снова и создайте экземпляр dbContext - _dbContext.ContextCounter = 1

Цель состоит в том, чтобы иметь новый экземпляр dbContext после каждого отдельного вызова метода wcf. Как я могу этого добиться?

Спасибо!


person mirt    schedule 08.01.2012    source источник
comment
Можете ли вы перефразировать это: Проблема в том, что после вызова метода wcf экземпляр DBContext сохраняется. Я хотел бы иметь новый экземпляр DBContext после каждого вызова метода wcf. Как я могу этого добиться? На самом деле непонятно, о чем вы просите и какое поведение вы наблюдаете сейчас   -  person Ladislav Mrnka    schedule 09.01.2012
comment
Я согласен с предыдущим комментарием. Судя по тому, как я прочитал ваш вопрос, он должен делать то, что вы хотите. PerWcfOperation означает, что экземпляр IDBContext привязан к текущему запросу / методу WCF.   -  person Sneal    schedule 09.01.2012
comment
Например: 1) Вызов wcf-метода CustomerGetById (), создается экземпляр dbcontext 2) Вызов wcf-метода ProductGetById (), теперь у меня есть тот же экземпляр dbcontext, что и раньше. Цель - получить новый. Спасибо!   -  person mirt    schedule 09.01.2012


Ответы (2)


Следующий код зарегистрирует компонент как стиль жизни PerWebRequest в WindsorContainer.

    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>
person Anand    schedule 09.01.2012
comment
Я пробовал использовать следующее: Component.For ‹IDBContext› () .ImplementedBy ‹DBContext› () .LifeStyle.PerWebRequest, но он не работает - person mirt; 16.01.2012

Пытаться:

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

У меня работает, но я не могу понять, как я скажу Виндзору использовать поведение службы, которое я определил в службе.

person Iron    schedule 24.07.2014