Search code examples
castle-windsorioc-containertransient

windsor component for is not working as transient


We are using windsor to register a instance for the IUnitOfWorkinterface. UnitOfWorkContainer.Current is a static method which returns an instance of IUnitOfWork.

 container.Register(Component.For<IUnitOfWork>()
            .Instance(UnitOfWorkContainer.Current)
                .LifeStyle.Transient);

The problem is UnitOfWorkContainer.Current is called only ones.


Solution

  • You're doing it wrong

    You are giving Windsor a pre-existing instance. Hence it is not creating it - it's reusing the instance you've given it.

    In other words, your code could be rewritten to the equivalent:

    var theOneAndOnly = UnitOfWorkContainer.Current;
     container.Register(Component.For<IUnitOfWork>()
                .Instance(theOneAndOnly)
                    .LifeStyle.Transient);
    

    I think what you really meant was:

     container.Register(Component.For<IUnitOfWork>()
                .UsingFactoryMethod(() => UnitOfWorkContainer.Current)
                    .LifeStyle.Transient);