如何在调用Resolve时使CastleWindsor创建一个新实例

Stu*_*ens 3 c# castle-windsor ioc-container

我有以下代码:

public interface IService { }
public class MyService : IService { }
Run Code Online (Sandbox Code Playgroud)

和测试方法

[Test]
public void T1()
{
    IWindsorContainer container = new WindsorContainer();

    container.Register(Component.For<IService>()
        .ImplementedBy<MyService>());

    var s1 = container.Resolve<IService>();
    var s2 = container.Resolve<IService>();
    Assert.AreNotSame(s1, s2);
}
Run Code Online (Sandbox Code Playgroud)

我应该更改测试通过什么?

jas*_*son 5

将生活方式设定为Transient:

container.Register(
    Component.For<IService>()
             .ImplementedBy<MyService>()
             .LifeStyle.Transient
);
Run Code Online (Sandbox Code Playgroud)

默认的生活方式是Singleton,这就是你看到同一个实例的原因.

  • @Paulo Santos:对不起,但测试通过了.我不知道你在说什么. (5认同)