I've hurt my brain here.
Some background:
I have a multiple services in multitier app. Some of them are short-living (and should be consumed with using
) and some of them are not (so I just inject them in any class I want and use directly). My client code has different data interfaces and random using
keywords.
For some reasons (for SCIENCE mostly) I decided to refactor it a bit. I've made an universal DataServiceAdapter<>
class which should be closed for every single service I use and this universal class encapsulate using
logic from client.
DataServiceAdapter
looks like this (short working example here on dotnetfiddle)
public class DataServiceAdapter<TService> : IDataService
where TService : IDataService, new()
{
private readonly TService _service;
private readonly Func<Func<TService, dynamic>, dynamic> _run;
public DataServiceAdapter()
{
if (typeof(IDisposable).IsAssignableFrom(typeof(TService)))
{
_run = RunWithUsing;
}
else
{
_service = new TService();
_run = RunWithoutUsing;
}
}
public bool Foo()
{
return _run(x => x.Foo());
}
public int Bar(string arg)
{
return _run(x => x.Bar(arg));
}
private dynamic RunWithUsing(Func<TService, dynamic> func)
{
using (var service = (IDisposable) new TService())
{
return func((TService)service);
}
}
private dynamic RunWithoutUsing(Func<TService, dynamic> func)
{
return func(_service);
}
}
public interface IDataService
{
bool Foo();
int Bar(string arg);
}
client supposed to work with it like this:
//class variable. Get this from IoC container
private readonly IDataService _service;
//somewhere in methods
var resultData = _service.Foo(); //full static type checking
But because my real life version of IDataService
contains dozens of method I rewrote DataServiceAdapter
like this (only changes, dotnetfiddle link):
public class DataServiceAdapter<TService> : IDataServiceAdapter<TService>
where TService : IDataService, new()
{
public dynamic Run(Func<TService, dynamic> func)
{
return _serviceUsing(func);
}
}
public interface IDataServiceAdapter<out TService>
where TService : IDataService
{
dynamic Run(Func<TService, dynamic> func);
}
client now works with that version of DataServiceAdapter
this way:
//class variable. Get this from IoC container
private readonly IDataServiceAdapter<IDataService> _service;
//somewhere in methods
var resultData = _service.Run(s => s.Foo());
It works without static checking because of dynamic
So (we are close to question) I decided to rewrote it again (for SCIENCE) and return static safety, but without necessity of wrapping all IDataService
methods in my adapter class.
First of all I wrote this delegate
:
private delegate TRes RunDelegate<TResult>(Func<TService, TResult> func);
But I just cant create variable of such delegate and pass it some method I wish to use like I did above.
Question:
Is there any way to implement my design thought there (generic service provider which call whether method with using
or method without it and has type-safety)?