Lets say I have a simple code like this (fiddleLink):
using System;
public class Program
{
public static void Main()
{
//Dependency register logic here
var service = new DataServiceAdapter();
var client = new Client(service);
Foo(client);
}
//Work class
public static void Foo(Client client)
{
client.ClientMethod();
}
}
public class Client
{
private readonly IDataService _service;
public Client(IDataService service)
{
_service = service;
}
public void ClientMethod()
{
Console.WriteLine(_service.Method());
Console.WriteLine(_service.Method2("Hello"));
}
}
internal class DataServiceAdapter : IDataService
{
public bool Method()
{
using (var something = new SpecifiDataService())
{
return something.Method();
}
}
public int Method2(string arg)
{
using (var something = new SpecifiDataService())
{
return something.Method2(arg);
}
}
}
public class SpecifiDataService : IDataService, IDisposable
{
public bool Method()
{
return true;
}
public int Method2(string arg)
{
return arg.Length;
}
public void Dispose()
{
//Dispose logic here
}
}
public interface IDataService
{
bool Method();
int Method2(string arg);
}
Goal I want to achieve is to encapsulate using
logic from client somewhere else (specifically in DataServiceAdapter
class).
Is there any way to write using
statement only once and not repeat it in every single method?
P.S. SpecifiDataService
may be WCF client service or DbContext of EntityFramework. Both should have short lifespans so I cant just open connection once and work with it.
P.P.S I can't reuse SpecificDataService
because in real case it will be WCF proxy-client or EntityFramework DbContext
implementation. Both cases contains dozens of method calls, so I have to write using
statements everywhere. First of all I want to free my client class from implementation of service. It should work both with short living services and long living ones. Another thing I tried to achieve - write methods without using
because its boring copy-paste in every single method
Dispose
method? If it is third-party code, please try your best to describe what it might do, according to your understanding. The purpose is to evaluate the tradeoffs of deferring the dispose, i.e. to keep theIDataService
objects alive for a longer time, possibly across multiple function calls.SpecifiDataService
may be WCF client service or DbContext of EntityFramework. Both should have short lifespans so I cant just open connection once and work with it.