1

に問題がありReuseScope.Requestます。を指定しても、すべてのリクエストで同じReuseScope.Requestインスタンスが注入されます。MasterConfig を取得するために、次の 2 つの呼び出しを使用してコンテナーを構成しました。

this.container.RegisterAutoWiredAs<ApiConfigFactory, IConfigFactory>().ReusedWithin(ReuseScope.Container);
this.container.Register(c => c.Resolve<IConfigFactory>().GetMasterConfig(true)).ReusedWithin(ReuseScope.Request);

GetMasterConfig(true) メソッドは、新しい具体的な MasterConfig を返します。ただし、サービスで MasterConfig を使用しようとすると、すべてのリクエストで同じインスタンスが取得されます。

public class MyService
{
    private readonly MasterConfig masterConfig;

    public SaleService(MasterConfig masterConfig)
    {
        this.masterConfig = masterConfig;
    }

    public object Post(MyRequest request)
    {
        // **masterConfig is the same instance here on every request**
    }
}

MasterConfig Register のスコープを に変更するとReuseScope.None、期待どおりに新しい MasterConfig が読み込まれます。私は何が欠けていますか?MasterConfig の登録方法に問題はありますか? ReuseScope.Noneが問題を解決するのはなぜですか? ReuseScope.Requestが同じインスタンスを表示するのはなぜですか?

ノート:

4

2 に答える 2

0

セルフホストまたは ASP.NET ホストでこれを再現できませんでした。

これは、ServiceStack の最新バージョンで機能します。

//AppHost
public class RequestScopeAppHost : AppSelfHostBase
{
    public RequestScopeAppHost() 
      : base(typeof(RequestScopeAppHost).Name, typeof(RequestScopeService).Assembly) {}

    private static int counter = 0;

    public override void Configure(Container container)
    {
        container.Register(c => new MasterConfig {
            Id = Interlocked.Increment(ref counter)
        }).ReusedWithin(ReuseScope.Request);
    }
}

サービス:

public class MasterConfig
{
    public int Id { get; set; }
}

public class GetMasterConfig : IReturn<MasterConfig> { }

public class RequestScopeService : Service
{
    private readonly MasterConfig config;

    public RequestScopeService(MasterConfig config)
    {
        this.config = config;
    }

    public object Any(GetMasterConfig request)
    {
        return config;
    }
}

テスト:

[TestFixture]
public class RequestScopeIssue
{
    private readonly ServiceStackHost appHost;

    public RequestScopeIssue()
    {
        appHost = new RequestScopeAppHost()
            .Init()
            .Start(Config.AbsoluteBaseUri);
    }

    [TestFixtureTearDown]
    public void TestFixtureTearDown()
    {
        appHost.Dispose();
    }

    [Test]
    public void Can_get_RequestScope_dependency()
    {
        var client = new JsonServiceClient(Config.AbsoluteBaseUri);

        Assert.That(client.Get(new GetMasterConfig()).Id, Is.EqualTo(1));
        Assert.That(client.Get(new GetMasterConfig()).Id, Is.EqualTo(2));
        Assert.That(client.Get(new GetMasterConfig()).Id, Is.EqualTo(3));
    }
}

あなたの説明ReuseScope.Noneでも意図したとおりに機能し、インスタンスを再利用しません。

于 2015-08-18T05:08:46.787 に答える