Developer
Developer

Reputation: 13

ServiceStack automatic dispose

I'm new to ServiceStack and I was trying to use it. I have a question to do: from the documentation I read that "ServiceStack only calls Dispose() on dependencies resolved within ServiceStack Requests, i.e. it tracks any disposables resolved from Funq and disposes of them at the end of a ServiceStack request.". What does it mean? Below you can see my example code: in this case, I was trying to dispose of JsonServiceClient using lazy property in the base class, but Dispose() not being invoked. Could you explain to me how does it work?

class Program
{
    static void Main(string[] args)
    {
        new AppHost().Init();
        var test = HostContext.AppHost.Container.TryResolve<Worker>();
        test.DoWork();
    }
}

public abstract class BaseWorker : IDisposable
{
    private JsonServiceClient client;
    public JsonServiceClient Client => client ??  (client = new JsonServiceClient());

    public virtual void Dispose()
    {
        client?.Dispose();
    }
}

public class Worker : BaseWorker
{
    public void DoWork()
    {
        var res = Client.ToPostUrl();
    }
}

public class AppHost : AppHostBase
{

    public AppHost() : base("Services", typeof(AppHost).Assembly)
    { }

    public override void Configure(Container container)
    {
        container.Register<Worker>(c => new Worker()).ReusedWithin(ReuseScope.Request);
    }
}

public class StoreGist : IReturn<StoreGistResponse> { }

public class StoreGistResponse
{
    public string Date { get; set; }
}

Thanks in advance.

Upvotes: 1

Views: 312

Answers (1)

mythz
mythz

Reputation: 143319

First of all you don't need to dispose JsonServiceClient as it doesn't retain any resources and its Dispose() is a NOOP.

I'd also recommend against using Request Scoped dependencies, basically if your dependencies only use ThreadSafe dependencies register it as a singleton (the default):

container.AddSingleton(c => new Worker()); //Equivalent to:
container.Register(c => new Worker());

Otherwise register it as a transient dependency, e.g:

container.AddTransient(c => new Worker()); //Equivalent to:
container.Register(c => new Worker()).ReusedWithin(ReuseScope.None);

"ServiceStack only calls Dispose() on dependencies resolved within ServiceStack Requests, i.e. it tracks any disposables resolved from Funq and disposes of them at the end of a ServiceStack request.". What does it mean?

It just means if ServiceStack is resolving and injecting your dependencies, e.g. in your ServiceStack Services, then ServiceStack will also dispose them. But if you're resolving dependencies from the IOC yourself you would need to explicitly dispose of them, typically with a using, e.g:

using var test = HostContext.AppHost.Container.TryResolve<Worker>();
test.DoWork();

Upvotes: 2

Related Questions