It is a standard practice to wrap your data functions in using statement while using entity framework. e.g.
using(var db = new MyAppContext())
{
return db.Books.ToList();
}
Often inside there is only one return statement. Is there a way to do this without having to write the using statement every time. With new c# feature the function will be much simpler to write.
public IList<Book> GetAllBooks() => db.Books.ToList()
There are lots and lots of methods I have that use this using block like that and if there is a way to do without it, it will make code much simpler.
Thank you in advance.
I can't say that I fully approve of what you're wanting, but, the following code:
public static class Extensions
{
public static TOut DisposeWrapper<TDisposable, TOut>(this TDisposable input, Func<TDisposable,TOut> function) where TDisposable:IDisposable
{
try
{
return function(input);
}
finally
{
input.Dispose();
}
}
}
Alternately, you can wrap in using, which has the exact same effect and is perhaps a bit more terse:
public static class Extensions
{
public static TOut DisposeWrapper<TDisposable, TOut>(this TDisposable input, Func<TDisposable,TOut> function) where TDisposable:IDisposable
{
using (input) return function(input);
}
}
Will let you do something similar to what you're wanting. It's slightly verbose to use, example:
public static int ExampleUsage() => new Example().DisposeWrapper(x => x.SomeMethod());
And for completeness, here's the example class I used to test this functionality:
public class Example : IDisposable
{
public void Dispose()
{
Console.WriteLine("I was disposed of");
}
public int SomeMethod() => 1;
}